【问题标题】:C++ parameter pack fails to expandC ++参数包无法展开
【发布时间】:2015-06-06 09:20:17
【问题描述】:

我正在使用可变参数模板,但我不明白为什么以下代码无法编译(GCC 4.9.2 with std=c++11):

这只是一个例子,但我需要在我的代码中使用类似的方法,它也失败了:

template<int I>
class Type{};
template<typename ... Tlist>
class A{
    public:
        template<int ...N>
            void a(Type<N> ... plist){

            }
};
template<typename ... Tlist>
class B{
public:
    template<int ... N>
        void b(Type<N> ... plist){
            A<Tlist...> a;
            a.a<N...>(plist ...);
        }
};

以及使用示例:

B<int, int, int> b;
b.b<1,7,6>(Type<1>(),Type<7>(),Type<6>());

我收到以下错误:

file.cpp: In member function ‘void B<Tlist>::b(Type<N>...)’:
file.cpp:58:9: error: expected ‘;’ before ‘...’ token
    a.a<N...>(plist ...);
         ^
file.cpp:58:24: error: parameter packs not expanded with ‘...’:
    a.a<N...>(plist ...);
                        ^
file.cpp:58:24: note:         ‘N’

但是下面的代码编译得很好(我只是从两个类中删除了 Tlist 参数并相应地调整了代码):

template<int I>
class Type{};
class A{
    public:
        template<int ...N>
            void a(Type<N> ... plist){

            }
};
class B{
public:
    template<int ... N>
        void b(Type<N> ... plist){
            A a;
            a.a<N...>(plist ...);
        }
};


B b;
b.b(Type<1>(),Type<7>(),Type<6>());

谁能给我一个解释? 谢谢。

【问题讨论】:

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


    【解决方案1】:

    编译器没有理由相信a.a 是一个模板;因此,必须将&lt; 解释为小于运算符。写:

            a.template a<N...>(plist ...);
              ^^^^^^^^^
    

    在您的第二个示例中,它知道a.a 是一个模板,因为那里的a 的类型不依赖于模板参数。

    【讨论】:

    • 天哪,我不敢相信它这么简单 :-) 非常感谢!当计时器用完时,我会接受你的回答。
    猜你喜欢
    • 2014-03-25
    • 2018-03-04
    • 2017-06-22
    • 1970-01-01
    • 2014-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    相关资源
    最近更新 更多