首页 > 解决方案 > 有没有办法从专门的构造函数调用模板构造函数?

问题描述

假设我有这门课:

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 = 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; }

标签: c++c++11templates

解决方案


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

您可以创建一个私有构造函数,它接受指针 fortintfor 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*/ }

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

不,那是不可能的。当您特化一个函数模板时,您并没有创建一个新函数,而是指定如果T推导出为您在特化中指定的类型,则使用特化定义代替泛型定义。

这就是为什么我有“所有三个构造函数”(泛型和两个特化)调用Test(T* t, int i),它处理所有案例共享的代码。


推荐阅读