6

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

这可以通过示例得到最好的证明:

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>)’
4

2 回答 2

2

大括号括起来的初始化列表不能被转发,所以不幸的是你不走运。

于 2012-08-12T12:30:54.100 回答
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?)
于 2012-08-12T11:54:11.933 回答