Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 类中有多个泛型类型_C++ - Fatal编程技术网

C++ 类中有多个泛型类型

C++ 类中有多个泛型类型,c++,C++,我有这些结构 typedef struct { int a; } a; typedef struct { char a; } aa; typedef struct { short b; } b; typedef struct { char b; } bb; class Test { private: a i; //or b i; aa c; // or bb c; } 我想创建一个具有相同代码的类,并根据类的声明使用a,aastructs或b,bbstructs,我不想单独模板化

我有这些结构

typedef struct {
 int a;
} a;
typedef struct {
 char a;
} aa;
typedef struct {
 short b;
} b;
typedef struct {
 char b;
} bb;

class Test {
private:
 a i; //or b i;
 aa c; // or bb c;
}

我想创建一个具有相同代码的类,并根据类的声明使用
a,aa
structs或
b,bb
structs,我不想单独模板化类中的每个函数,我想让类在调用构造函数之前或构造函数中知道要使用哪一组结构,怎么做?谢谢。

我不确定我是否完全理解这个问题,但你是否在寻找类似的东西

#include <type_traits>

template <bool UseA>
class Test {
private:
 typename std::conditional<UseA, a, b>::type i;
 typename std::conditional<UseA, aa, bb>::type c;
};

Test<true> test_using_a;
Test<false> test_using_b;
#包括
模板
课堂测试{
私人:
typename std::conditional::type i;
typename std::conditional::type c;
};
使用_a测试_;
使用_b测试_;

拥有两个不同类型成员的一般解决方案当然是:

template<class X, class Y>
class Test {
private:
   X i;
   Y c;
};
模板
课堂测试{
私人:
xi;
Y-c;
};

然后你可以实例化你想要的任何组合,比如
Test
Test
,或者甚至疯狂地使用
Test

你也不想让整个类成为
模板
?是否将类转换为类模板是一个选项?是的,将类转换为模板很好