简体   繁体   English

C ++创建动态类型

[英]c++ create dynamic type

I have the following situation: Depending on some parameter that my function takes it have to create different types: 我有以下情况:根据我的函数采用的某些参数,必须创建不同的类型:

I want to do something like this: 我想做这样的事情:

if(variant==1){
    #define my_type int;
}
else{
    #define my_type double;
}
cout<<sizeof(my_type);

and then use my_type in my further code. 然后在我的后续代码中使用my_type。

So, that in case of variant=1 sizeof(my_type) gives 4 and for variant=2 it gives 8. 因此,如果variant = 1, sizeof(my_type)给出4,而variant = 2给出8。

How can this be done? 如何才能做到这一点? Either in this manner or another. 以这种方式或其他方式。

Thanks. 谢谢。

I agree with @Magnus Hoff in that what you asked cannot be done. 我同意@Magnus Hoff的观点,因为您要求的内容无法完成。 But there are two approximations. 但是有两个近似值。

Option 1: make variant a macro. 选项1:将变体设为宏。

#ifdef variant
#  define my_type int
#else
#  define my_type double
#endif

Option 2: use template function. 选项2:使用模板功能。

Instead of 代替

void func(int variant) {
  if (variant==1)
    #define my_type int
  else
    #define my_type double
  my_type ...
}

do this: 做这个:

template<typename my_type> void func() {
  my_type ...
}        

Replace this: 替换为:

if(variant==1){
    #define my_type int;
}
else{
    #define my_type double;
}
cout<<sizeof(my_type);

… with this: … 有了这个:

template< class Type >
void foo()
{
    // ...
    cout<<sizeof(Type);
}

// ...
if( variant==1 )
{
    foo<int>();
}
else
{
    foo<double>();
}

Note that a runtime value can't affect compile time decisions. 请注意,运行时值不会影响编译时间决策。 Without a time travel device. 没有时间旅行装置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM