gpt4 book ai didi

c++ - 如何从 if 语句中获取类模板的实例? (C++)

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:20:52 25 4
gpt4 key购买 nike

假设我有一个类模板,它有一个成员 pData,它是一个任意类型 TAxB 数组。

template <class T> class X{ 
public:
int A;
int B;
T** pData;
X(int a,int b);
~X();
void print(); //function which prints pData to screen

};
template<class T>X<T>::X(int a, int b){ //constructor
A = a;
B = b;
pData = new T*[A];
for(int i=0;i<A;i++)
pData[i]= new T[B];
//Fill pData with something of type T
}
int main(){
//...
std::cout<<"Give the primitive type of the array"<<std::endl;
std::cin>>type;
if(type=="int"){
X<int> XArray(a,b);
} else if(type=="char"){
X<char> Xarray(a,b);
} else {
std::cout<<"Not a valid primitive type!";
} // can be many more if statements.
Xarray.print() //this doesn't work, as Xarray is out of scope.
}

由于实例 Xarray 是在 if 语句中构建的,所以我无法在其他任何地方使用它。我试图在 if 语句之前创建一个指针,但由于此时指针的类型未知,所以我没有成功。

处理此类问题的正确方法是什么?

最佳答案

这里的问题是 X<int>x<char>是完全不相关的类型。

它们都是同一个模板类的结果这一事实在这里无济于事。

我可以看到几种解决方案,但这取决于您真正需要什么。

例如,您可以制作 X<>实例派生自具有 print() 的公共(public)非模板化基类方法(最终作为纯虚拟)。但在这样做之前,请确保它在功能层面上有意义:应该使用继承是因为它有意义,而不仅仅是因为技术限制。如果这样做,您可能还希望拥有一个虚拟析构函数。

您还可以绑定(bind)并存储 std::function<void ()>到你想调用的方法,但确保对象仍然“活着”(它们不在你当前的代码中:X<int>X<char> 在它们超出范围时被销毁,远远早于你实际调用 print() )。

最终的解决方案是制作一些与 X<int> 兼容的变体类型和 X<char> ( boost::variant<> 可以在这里提供帮助)。然后您可以编写一个实现 print() 的访问者每种类型的功能。

选择最后一个解决方案,它会变成这样:

typedef boost::variant<X<int>, X<char>> genericX;

class print_visitor : public boost::static_visitor<void>
{
public:
template <typename SomeType>
void operator()(const SomeType& x) const
{
// Your print implementation
// x is your underlying instance, either X<char> or X<int>.
// You may also make several non-templated overloads of
// this operator if you want to provide different implementations.
}
};

int main()
{
boost::optional<genericX> my_x;

if (type=="int") {
my_x = X<int>(a,b);
} else if(type=="char") {
my_x = X<char>(a,b);
}

// This calls the appropriate print.
if (my_x) {
boost::apply_visitor(print_visitor(), *my_x)
}
}

我们实际上缺乏给出明确答案的知识:如果你的类是“实体”,那么你可能应该去继承。如果它们更像是“值类”,那么变体方式可能更适合。

关于c++ - 如何从 if 语句中获取类模板的实例? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14980042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com