Restrict variadic template arguments

前端 未结 5 770
旧时难觅i
旧时难觅i 2020-12-02 08:58

Can we restrict variadic template arguments to a certain type? I.e., achieve something like this (not real C++ of course):

struct X {};

auto foo(X... args)
         


        
5条回答
  •  既然无缘
    2020-12-02 09:38

    You already have it since C++11 standard.

    A simple std::array (special case of std::tuple where all the tuple elements share the same type) will be sufficient.

    However, if you want to use it in a template function, you may better use an ´std::initializer_list` like in the following example:

    template< typename T >
    void foo( std::initializer_list elements );
    

    This is a really simple solution which solves your problem. Using variadic template arguments is an option too, but adds unnecessary complexity to your code. Remember that your code should be readable by others, including yourself after some time.

提交回复
热议问题