Mat*_*Mat 8 c++ generics templates types dynamic
有没有办法在运行时选择类的泛型类型,还是在C++中这是一个编译时的东西?
我想做的是像这样(伪代码):
Generictype type;
if(somveval==1)
type = Integer;
if(someval==2)
type = String;
list<type> myList;
Run Code Online (Sandbox Code Playgroud)
这在C++中是否可行?如果是,怎么样?
Cha*_*via 11
这是一个编译时间的事情.编译时必须知道模板参数类型.
也就是说,使用某些模板元编程技术,您可以选择一种类型或另一种AT编译时,但只有在编译时才知道所有可能的类型,并且只有在可以解决选择类型的条件时在编译时.
例如,使用部分特化,您可以在编译时根据整数选择一个类型:
template <typename T>
class Foo
{ };
template <int N>
struct select_type;
template<>
struct select_type<1>
{
typedef int type;
};
template<>
struct select_type<2>
{
typedef float type;
};
int main()
{
Foo<select_type<1>::type> f1; // will give you Foo<int>
Foo<select_type<2>::type> f2; // will give you Foo<float>
}
Run Code Online (Sandbox Code Playgroud)