在运行时可以选择C ++通用类型参数吗? [英] Is it possible to choose a C++ generic type parameter at runtime?

查看:137
本文介绍了在运行时可以选择C ++通用类型参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想做什么是一些事情,这是一个在运行时选择类的通用类型的方法,像这样(伪代码):

  Generictype type; 
if(somveval == 1)
type = Integer;
if(someval == 2)
type = String;

list< type>我的列表;

这是否可能在C ++中?如果是,怎么样?

解决方案

这是一个编译时间。模板参数类型必须在编译时被编译器知道。



这就是说,使用某些模板元编程技术,您可以选择一种类型或另一种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; //会给你Foo< int>
Foo< select_type< 2> :: type> F2; //会给你Foo< float>
}


Is there a way to choose the generic type of a class at runtime or is this a compile-time thing in C++?

What I want to do is something like this (pseudocode):

Generictype type;
if(somveval==1)
    type = Integer;
if(someval==2)
    type = String;

list<type> myList;

Is this possible in C++? and if yes, how?

解决方案

It's a compile time thing. Template parameter types must be known to the compiler at compile-time.

That being, said, using certain template meta-programming techniques, you can choose one type or another AT compile-time, but only if all possible types are known at compile-time, and only if the condition for selecting a type can be resolved at compile time.

For example, using partial specialization you could select a type at compile time based on an integer:

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 ++通用类型参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆