C++11 variable number of arguments, same specific type

前端 未结 6 1835
难免孤独
难免孤独 2020-12-05 01:55

Question is simple, how would I implement a function taking a variable number of arguments (alike the variadic template), however where all arguments have the same type, say

6条回答
  •  无人及你
    2020-12-05 02:23

    I think you can do this by specifying a concrete type when chewing your arguments out of the argument pack. Something like:

    class MyClass{};
    class MyOtherClass{};
    
    void func()
    {
        // do something
    }
    
    template< typename... Arguments >
    void func( MyClass arg, Arguments ... args )
    {
        // do something with arg
        func( args... );
        // do something more with arg
    }
    
    
    void main()
    {
        MyClass a, b, c;
        MyOtherClass d;
        int i;
        float f;
    
        func( a, b, c );    // compiles fine
        func( i, f, d );    // cannot convert
    }
    

    In the generic case void func( MyClass arg, Arguments ... args ) would become void func( arg, Arguments ... args ) with a template type T.

提交回复
热议问题