假设我有这门课:
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; }
最佳答案
您可以使用 delegating constructor为了这。
您可以创建一个私有(private)构造函数,该构造函数采用 t
的指针。 , 和 int
为 i
.然后你可以用它来设置 x
和 i
,并运行所有共享代码。
那看起来像:
template <class T>
class Test
{
public:
Test(T* x) : Test(x, 0) { /*code for default case, runs after delegate*/ }
private:
Test(T* t, int i) : t(t), i(i) { /*code to run for everything*/ }
const T* const t;
int i;
};
template <> Test<Foo>::Test(Foo* x) : Test(x, 1) { /*code only for Foo, runs after delegate*/ }
template <> Test<Foo>::Test(Bar* x) : Test(x, 2) { /*code only for Bar, runs after delegate*/ }
委托(delegate)构造函数是否可以是泛型/模板化构造函数(与 Foo 和 Bar 的特定专用构造函数具有相同的签名)? 不,那是不可能的。当您专门化一个函数模板时,您不是在创建一个新函数,而是指定 if
T
被推导为您在特化中指定的类型,然后使用特化定义代替通用定义。这就是为什么我有“所有三个构造函数”(泛型和两个特化)调用
Test(T* t, int i)
,它处理所有情况共享的代码。
关于c++ - 有没有办法从专门的构造函数调用模板构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69208445/