gpt4 book ai didi

c++ - 是否可以在运行时选择 C++ 泛型类型参数?

转载 作者:可可西里 更新时间:2023-11-01 18:18:12 26 4
gpt4 key购买 nike

有没有办法在运行时选择类的泛型类型,或者这是 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/

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