将专业化定义为另一个类的实例化
Define a Specialization As Instantiation of Another Class
我有一种情况,我想将一个专门化定义为与另一个类的实例化相同。这里有一个我想要的简单例子(在这个例子中是一个完整的术语;在我的实际问题中,我想要一个部分专业化):
//Template class
template <int i> class Foo { /*...*/ };
//Another, completely different, template class
template <int i,int j> class Bar { /*...*/ };
//Ordinary specialization of Foo
template <> class Foo<0> { /*...*/ };
//Bogus specializations of Foo that
// hopefully explain what I want.
template <> class Foo<1> = Bar<1, 11>;
template <> class Foo<2> = Bar<2, 42>;
template <> class Foo<3> = Bar<3,-71>;
...
这样做有什么好处?Foo<1>
、Foo<2>
等的定义相当复杂,但很容易作为模板编写一次。有很多这样的定义。将Bar
的定义转换为Foo
不是一种选择。只有一些值可以专门化,并且Bar
的专门化必须手工选择(因此int j
的随机数)。
我通常会通过使用CRTP来达到这种效果。我会对Bar
进行一些相当恶劣的修改,然后做一些类似的事情:
template <> class Foo<1> : public Bar<1, 11,Foo<1>> {};
template <> class Foo<2> : public Bar<2, 42,Foo<2>> {};
template <> class Foo<3> : public Bar<3,-71,Foo<3>> {};
...
显然,Bar
需要更改,可能需要一些using
声明来降低构造函数。这会很混乱。
我的问题是:我能做得更好吗?也就是说,一个专门化可以被定义为另一个模板类的实例化吗?
注意:首选的标准是C++14,尽管可以接受更高版本
间接寻址在这里有帮助吗?:)
template<int i> struct Indirection { using type = Foo<i>; };
template <> class Indirection<1> { using type = Bar<1, 11>; };
template <> class Indirection<2> { using type = Bar<2, 42>; };
template <> class Indirection<3> { using type = Bar<3, -71>; };
template<int i>
using ActualFoo = typename Indirection<i>::type;
您可以使用继承而不是CRTP。
template <int i> struct Foo {};
template <int i,int j> struct Bar { Bar() {} };
template <> struct Foo<0> {};
template <> struct Foo<1> : public Bar<1, 11> { using Bar::Bar; };
template <> struct Foo<2> : public Bar<2, 42> { using Bar::Bar; };
template <> struct Foo<3> : public Bar<3,-71> { using Bar::Bar; };
相关文章:
- 如果模板参数是另一个模板的实例化,则键入特征测试
- 我有一个类,它创建了另一个类的实例.如何将变量通过第一个类传递到第二个类的实例化中?
- 有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?
- 如何正确实例化静态字段 tat 是另一个类对象
- C++入门5版:使用get成员初始化另一个与shared_ptr无关的对象
- 连接类实例和另一个类实例中的对话框之间的槽和信号
- 如何使用构造函数初始化另一个类的对象
- 初始化另一个类中的类的对象
- 将类实例作为另一个类参数传入
- 如何在类的构造函数中将对象实例化为另一个类?C++
- 我可以初始化另一个类中的类吗?
- 当用于初始化另一个对象时,为什么要按值传递参数
- 一个实例影响另一个实例,尽管它不应该't
- 不能在c++中从main实例化另一个类
- 如何在c++中从一个实例访问另一个实例的信息
- 如何创建知道它的实例在另一个类的矩阵中的方法
- (复制构造函数)作为参数传递给初始化另一个对象的对象如何访问私有成员
- 保存一个对象的变量,然后可以用这些变量初始化另一个对象
- 初始化另一个变量或反复使用原始变量
- 类的多个实例使用另一个类的单个实例