gpt4 book ai didi

c++ - 在运行时有条件地实例化模板

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

我有一个模板类


template <class T>
class myClass
{
public:
/* functions */
private:
typename T::Indices myIndices;
};

Now in my main code I want to instantiate the template class depending on a condition. Like :


myFunc( int operation)
{
switch (operation) {
case 0:
// Instantiate myClass with <A>
auto_ptr < myClass <A> > ptr = new myClass<A> ();
case 1:
// Instantiate myClass with <B>
auto_ptr < myClass <B> > ptr = new myClass<B> ();
case 2:
// Instantiate myClass with <C>
....
}
// Use ptr here..
}

现在这种方法的问题是 auto_ptr<>将在 switch{} 结束时死去.而且我不能在函数的开头声明它,因为我不知道将事先实例化的类型。

我知道我正在尝试在编译时(使用模板)实现运行时的事情,但仍然想知道是否有更好的方法来做到这一点。

最佳答案

创建基类

class Base {     
protected:
virtual ~Base() {}
//... functions
};

template <class T> class myClass : Base {
//...
};

myFunc( int operation){
shared_ptr < Base > ptr;

switch (operation) {
case 0:
// Instantiate myClass with <A>
ptr.reset ( new myClass<A> () );
case 1:
// Instantiate myClass with <B>
ptr.reset ( new myClass<B> () ) ;
case 2:
// Instantiate myClass with <C> ....
}
// Use ptr here..
}

关于c++ - 在运行时有条件地实例化模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1807360/

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