c++ - 代理类模板具有与表示类相同的构造函数签名
问题描述
如何编写通用/模板化代理类P
,使其具有与某些表示类相同的构造函数签名C
,并将这些参数从P
原样转发C
,而无需任何运行时开销?
(因为P
是通用的,C
构造函数可以有任意数量和类型的参数,甚至没有)。
示例代码:
class C {
public:
C(int i, string s, bool b,... /* assorted number and types of arguments, maybe none */) {
/* ... */
}
/* other methods */
};
template<typename T>
class P {
public:
P(/* same arguments of T constructor */) {
// get a T instance
T t(/* forward arguments from P constructor, unaltered */);
/* ... */
}
/* other methods */
};
使用 P:
P<C> p{/* arguments required by C */};
p.some_p_method();
解决方案
可以使用私有继承和using
关键字来“导入”构造函数 from C
into P
:
template<typename T>
class P : private T
{
public:
using T::T; // "Import" the T constructors
// ...
};
P
请注意,如果您需要代理类在其自己的构造中包含一些特殊的初始化,则此方案将不起作用。
推荐阅读
- django - url 中的 Django 尾部斜杠无法正常工作
- javascript - PDFKit 插件的阿拉伯语文本问题
- python - ImportError:没有模块命名无法在python中导入模块的顶级目录
- node.js - 切换到表单提交反应的新页面
- oozie - 即使先前的操作未成功完成,如何从特定操作运行 Oozie 工作流
- python - 使用 Pandas 重命名 excel 的列
- python - 如何通过 FileInput Bokeh 更新滑块值
- php - 使用 Laravel 排序和分组
- sqlite - 将(原始)Sqlite 与 .NET Core 5 的 VS 2019 NUUnit 测试项目结合使用
- c++ - 如何在 C++ 中获得特征矩阵运算符 + 的性能