首页 > 解决方案 > 代理类模板具有与表示类相同的构造函数签名

问题描述

如何编写通用/模板化代理类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();

标签: c++templates

解决方案


可以使用私有继承和using关键字来“导入”构造函数 from Cinto P

template<typename T>
class P : private T
{
public:
    using T::T;  // "Import" the T constructors
    // ...
};

P请注意,如果您需要代理类在其自己的构造中包含一些特殊的初始化,则此方案将不起作用。


推荐阅读