Non-type variadic function templates in C++11

前端 未结 5 1452
有刺的猬
有刺的猬 2020-12-05 23:48

I saw a blog post which used non-type variadic templates (currently not supported by gcc, only by clang).

template 
stru         


        
5条回答
  •  心在旅途
    2020-12-06 00:15

    Luc Danton's solution doesn't behave correctly with parameters which are not of type int, but can be implicitly converted to an int. Here's one which does:

    template struct first_type { typedef T type; };
    template int max_checked(T n) { return n; }
    template
    int max_checked(T1 n1, T2 n2, Ts ...ns)
    {
      int maxRest = max_checked(n2, ns...);
      return n1 > maxRest ? n1 : maxRest;
    }
    template auto max(T &&...t) ->
      decltype(max_checked::type...>(t...))
    {
      return max_checked::type...>(t...);
    }
    
    struct S { operator int() { return 3; } };
    int v = max(1, 2.0, S()); // v = 3.
    

    Here, max forwards all arguments unchanged to max_checked, which takes the same number of arguments of type int (provided by performing a pack-expansion on the first_type template). The decltype(...) return type is used to apply SFINAE if any argument can't be converted to int.

提交回复
热议问题