Restrict variadic template arguments

前端 未结 5 774
旧时难觅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条回答
  •  旧时难觅i
    2020-12-02 09:15

    How about static_assert and helper template method (c++11 solution):

    template 
    int assert_impl() {
       static_assert(b, "not convertable");
       return 0;
    }
    
    template 
    void foo_x(Args... args) {
        int arr[] {assert_impl::value>()...};
        (void)arr;
    }
    

    One more c++11 this one uses "one-liner" sfinae-based solution:

    template {typename std::enable_if::value, int>::type{}...})>
    void foo_x(Args... args) {
    }
    

提交回复
热议问题