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

标签 c++ c++11 templates

假设我有这门课:

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

最佳答案

您可以使用 delegating constructor为了这。
您可以创建一个私有(private)构造函数,该构造函数采用 t 的指针。 , 和 inti .然后你可以用它来设置 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*/ }
委托(delegate)构造函数是否可以是泛型/模板化构造函数(与 Foo 和 Bar 的特定专用构造函数具有相同的签名)?
不,那是不可能的。当您专门化一个函数模板时,您不是在创建一个新函数,而是指定 if T被推导为您在特化中指定的类型,然后使用特化定义代替通用定义。
这就是为什么我有“所有三个构造函数”(泛型和两个特化)调用 Test(T* t, int i) ,它处理所有情况共享的代码。

关于c++ - 有没有办法从专门的构造函数调用模板构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69208445/

相关文章:

c++ - 为什么我的运算符重载不能正常工作?

c++ - 当按值传递比通过 const 引用传递时的经验法则?

c++ - 如何使用 YouCompleteMe 在 vi​​m 中启用 C++ 模板类的完成

c++ - 使用公共(public)数据初始化多个 C++ 数组

c++ - 如何通过保存在容器中的成员函数指针来调用?

c++ - C++中初始化数组容器的方法

c++ - STL codecvt 错误 c++

c++ - 在模板中存储类成员函数

java - 缓存基本 XWPFDocument 模板并重用它们来生成文档

c++ - 在 Qt QProcess 中运行 sudo 命令