Enforce variadic template of certain type

后端 未结 4 1656
执念已碎
执念已碎 2020-12-31 02:35

I would like to enforce the type of variadic template to be identical to an earlier set template type. In the below example, I\'d like T and U to be the same type.

c

4条回答
  •  独厮守ぢ
    2020-12-31 03:27

    If all parameters are required to be the same type AND the number of parameters is variable,

    Variadic templates are too heavy for those requirements, just use C++11 std::initializer_list.

    They just do the job if you can replace () with {} on the call.

    template struct Foo {
        Foo(T val) {
            std::cout << "Called single argument ctor" << std::endl;
        }
        // Enforce all parameters to be the same type :
        Foo( std::initializer_list values ) {
            std::cout << "Called multiple argument ctor" << std::endl;
            for (T value : values)
                cout << value << endl;
        }
    };
    
    int main() {
        // Work as expected.
        Foo single(1);
        // Work as expected.
        Foo multiple{ 1, 2, 3, 4, 5 };
        // Doesn't work - as required :
        //Foo mixedtype{ 1, "a", "b", "c" };
    
    }
    

提交回复
热议问题