作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
有没有办法在运行时选择类的泛型类型,或者这是 C++ 中的编译时事情?
我想做的是这样的(伪代码):
Generictype type;
if(somveval==1)
type = Integer;
if(someval==2)
type = String;
list<type> myList;
这在 C++ 中可行吗?如果是,怎么做?
最佳答案
这是编译时的事情。编译器必须在编译时知道模板参数类型。
也就是说,使用某些模板元编程技术,您可以在编译时选择一种或另一种类型,但前提是所有可能的类型在编译时都是已知的,并且只有选择类型的条件可以在编译时解决。
例如,使用部分特化,您可以在编译时根据整数选择类型:
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>
}
关于c++ - 是否可以在运行时选择 C++ 泛型类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1735796/
我是一名优秀的程序员,十分优秀!