有没有办法从专门的构造函数调用模板构造函数?

T. *_*ers 4 c++ templates c++11

假设我有这门课:

template <class T>
class Test
{
    Test(T* x);

    const T* const t;
    int i{0};
};
Run Code Online (Sandbox Code Playgroud)

我希望t始终使用以下内容进行初始化x

template <class T> Test<T>::Test(T* x) : t{x} {}
Run Code Online (Sandbox Code Playgroud)

我有两个专业:

template <> Test<Foo>::Test(Foo* x) : t{x} { i = 1; }
template <> Test<Bar>::Test(Bar* x) : t{x} { i = 2; }
Run Code Online (Sandbox Code Playgroud)

接下来,我用其他一些东西扩展该类,第一个(模板化)构造函数所做的不仅仅是设置t.

所有我想做的事情都是为了T = FooT = 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; }
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 8

您可以为此使用委托构造函数。

您可以创建一个私有构造函数,它接受指针 fort和一个intfor i。然后您可以使用它来设置xi,并运行所有共享代码。

那看起来像:

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*/ }
Run Code Online (Sandbox Code Playgroud)

委托构造函数可以是通用/模板化构造函数(与 Foo 和 Bar 的特定、专用构造函数具有相同的签名)吗?

不,那是不可能的。当您专门化函数模板时,您并不是在创建新函数,而是指定如果T推导为您在专门化中指定的类型,则使用专门化定义代替通用定义。

这就是为什么我有“所有三个构造函数”(通用和两个专门化) call Test(T* t, int i),它处理所有情况共享的代码。