在可变参数模板中使用大括号括起来的初始化列表?

时间:2012-08-12 10:02:09

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

我正在尝试在可变参数模板函数中使用大括号括起来的初始化列表,但是编译器抱怨...我是在问太多还是我做错了什么?

最好通过示例来证明:

struct Bracy
{
    Bracy(int i, int j)
    {
    }
};

struct Test
{

    void consumeOne(int i)
    {
    }

    void consumeOne(const Bracy & bracy)
    {
    }

    void consume()
    {
    }

    template<typename T, typename ...Values>
    void consume(const T & first, Values... rest)
    {
        consumeOne(first);
        consume(rest...);
    }

    template<typename ...Values>
    Test(Values... values)
    {
        consume(values...);
    }
};

void testVariadics()
{
    Test(7,{1,2}); //I'd like {1,2} to be passed to consumeOne(const Bracy & bracy)
}
GCC(4.7)说:

main.cpp:45:14: error: no matching function for call to ‘Test::Test(int, <brace-enclosed initializer list>)’

2 个答案:

答案 0 :(得分:2)

括号封闭的初始化列表无法转发,因此您遗憾地运气不好。

答案 1 :(得分:0)

这是对你想要的一个粗略的尝试......

#include <iostream>
#include <initializer_list>

struct Bracy {
    Bracy(int x, int y) {}
};

struct Test {
    void consumeOne(std::initializer_list<int>) { std::cout << "initializer list version (Bracy?)\n"; /* Bracy? */}

    void consumeOne(int) { std::cout << "int version\n"; }

    template<typename T>
    void consume(T t) { consumeOne(t); }

    template<typename T, typename ... Args>
    void consume(T first, Args ... args) {
        consumeOne(first);
        consume(args...);
    }

    template<typename ... Args>
    Test(Args ... args) {
        consume(args...);
    }
};

int
main(int argc, char** argv) {
    Test(1, std::initializer_list<int>{1,2}, 2, 3, std::initializer_list<int>{1,2});
    return 0;
}

output: int version
        initializer list version (Bracy?)
        int version
        int version
        initializer list version (Bracy?)