Restrict variadic template arguments

前端 未结 5 766
旧时难觅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:21

    What about the following solution ?

    --- EDIT --- Improved following suggestion from bolov and Jarod42 (thanks!)

    #include 
    
    template 
    auto foo(Args... args) = delete;
    
    auto foo ()
     { return 0; }
    
    template 
    auto foo (int i, Args ... args)
     { return i + foo(args...); }
    
    int main () 
     {
       std::cout << foo(1, 2, 3, 4) << std::endl;  // compile because all args are int
       //std::cout << foo(1, 2L, 3, 4) << std::endl; // error because 2L is long
    
       return 0;
     }
    

    You can declare foo() to receive all types of arguments (Args ... args) but (recursively) implement it only for one type (int in this example).

提交回复
热议问题