Use brace-enclosed initializer lists in a variadic template?

后端 未结 2 692
无人及你
无人及你 2021-01-18 07:43

I\'m trying to use brace-enclosed initializer lists in a variadic template function, but the compiler complains... am I asking too much or did I do something wrong?

相关标签:
2条回答
  • 2021-01-18 08:15

    This is a rough attempt at what you want...

    #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?)
    
    0 讨论(0)
  • 2021-01-18 08:22

    A brace enclosed initializer list cannot be forwarded, so you are unfortunately out of luck.

    0 讨论(0)
提交回复
热议问题