c++ - 将 args 的参数包解包到可变参数模板中定义的每个类的构造函数中

标签 c++ c++11 variadic-templates

我正在尝试创建一个继承自多个类(由可变参数模板定义)的类,并且对于每个类,将相同的 args 参数包传递给每个类的构造函数。但是,似乎我无法同时解压缩类的可变参数模板和 args 的参数包。

我有一个类:

template<class... __Policies>
class GenericPolicyAdapter : public __Policies...{

使用构造函数:

template<class... __Args>
GenericPolicyAdapter( __Args... args ) : __Policies( args... ){

和测试:

GenericPolicyAdapter<T1,T2> generic_policy_adapter( arg1, arg2, arg3 );

gcc 失败:

error: type ‘__Policies’ is not a direct base of ‘GenericPolicyAdapter<T1,T2>’

其中 __Policies = T1, T2

澄清一下,我实际上是在尝试:

GenericPolicyAdapter : public T1, public T2
{
  public:
    template<class... __Args>
    GenericPolicyAdapter( __Args... args ) : T1( args... ), T2( args... ){}
};

但是 T1T2__Policies 中推导出来

有什么想法吗?似乎 gcc 将 __Policies 视为单一类型而不是类型列表。提前致谢!


编辑:

我应该澄清一下,我使用的是 gcc/g++ 4.4.5。

Howard Hinnant 的建议是:

template<class... __Args>
    GenericPolicyAdapter( __Args... args )
        : __Policies( args...)...
    {}

但是,对于 gcc/g++ 4.4.5,这会导致包扩展表达式的使用无效。这在 OSX/clang 中工作很好,但是有没有办法在 gcc/g++ 中做到这一点?

最佳答案

...”很像“typename”。你只需要继续积极地洒它直到事情编译。 :-)

template<class... __Policies>
class GenericPolicyAdapter
    : public __Policies...
{
public:
    template<class... __Args>
        GenericPolicyAdapter( __Args... args )
            : __Policies( args...)...
        {}
};

struct T1
{
    T1(int, int, int) {}
};

struct T2
{
    T2(int, int, int) {}
};

int main()
{
    GenericPolicyAdapter<T1,T2> generic_policy_adapter( 1, 2, 3 );
}

关于c++ - 将 args 的参数包解包到可变参数模板中定义的每个类的构造函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7694201/

相关文章:

c++ - 重载时区分函数

c++ - read方法从文件中返回最后一个对象两次

c++ - 为什么指针增量语句被优化掉了?

c++ - 向条件语句添加条件

c++ - 如何将 `duration_cast` 用于派生类?

c++ - 在 C++ 中重命名(别名/转发)函数的最佳方法是什么?

c++ - 创建指针数组时 operator new[] 的语法

c++ - 静态函数数组上未解析的外部符号

c++ - std::shared_ptr 中的计数器是原子的吗?

c++ - 使用 std::bind 和 std::placeholders 的可变模板工厂