c++ - 有没有办法从专门的构造函数调用模板构造函数?
问题描述
假设我有这门课:
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; }
解决方案
您可以为此使用委托构造函数。
您可以创建一个私有构造函数,它接受指针 fort
和int
for 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*/ }
委托构造函数可以是通用/模板化构造函数(与 Foo 和 Bar 的特定、专用构造函数具有相同的签名)吗?
不,那是不可能的。当您特化一个函数模板时,您并没有创建一个新函数,而是指定如果T
推导出为您在特化中指定的类型,则使用特化定义代替泛型定义。
这就是为什么我有“所有三个构造函数”(泛型和两个特化)调用Test(T* t, int i)
,它处理所有案例共享的代码。
推荐阅读
- javascript - findByType 函数找不到属性?
- git - 需要切换到 git 子模块中未列出的不同分支
- wpf - 将参数传递给 RelayCommand
- python - Python:IndentationError:unindent 不匹配任何外部缩进级别:文本到数字
- python - Is it okey to use lambda in this case?
- python - 有没有办法分解 CNN 模型以向人类提供预测见解?
- python - Python中参数界限的凸优化
- python-3.x - 在虚拟环境中运行 python 脚本
- gradle - Could not create service of type ChecksumService using BuildSessionScopeServices.createChecksumService()
- python-3.x - "worksheet.write" ı can not write excel