【发布时间】:2021-11-11 10:44:37
【问题描述】:
假设我有这门课:
template <class T>
class Test
{
Test(T* x);
const T* const t;
int i{0};
};
我希望 t 始终使用 x 进行初始化:
template <class T> Test<T>::Test(T* x) : t{x} {}
我有两个专业:
template <> Test<Foo>::Test(Foo* x) : t{x} { i = 1; }
template <> Test<Bar>::Test(Bar* x) : t{x} { i = 2; }
接下来,我用一些其他的东西来扩展这个类,第一个(模板化的)构造函数所做的不仅仅是设置t。
我想为T = Foo 和T = Bar 做的所有事情。
有没有什么方法可以从专门的构造函数中调用模板化构造函数?
//This does not work, since it will create a delegation cycle
template <> Test<Foo>::Test(Foo* x) : Test(x) { i = 1; }
template <> Test<Bar>::Test(Bar* x) : Test(x) { i = 2; }
【问题讨论】: