Home > OS >  How to enable auto nontype template parameter pack for same type of parameters
How to enable auto nontype template parameter pack for same type of parameters

Time:03-26

I have the following code:

template<auto... args> struct Custom
{
};
int main()
{
    Custom<1, nullptr> s; // i want this to succeed only when all the template arguments are of the same type    
}

As is evident from the above code, i can pass template arguments of different types. My question is that is there a way to only accept template arguments of the same type. This means, that the statement inside the main should fail and should only work when all the template arguments are of the same type. Essentially, there are 2 requirements:

  1. The code should not work for less than 1 template argument. That is, at least one template argument must be present. If the user provides 0 template arguments then it should not work.
  2. The code should not work for different type of template arguments.

I don't if this is even possible. I was thinking of maybe using enable_if or some other feature but i don't know what might help here.

CodePudding user response:

You can make use of the decltype construct as shown below:

template<auto T1, decltype(T1)... Args> struct Custom
{
};

Working Demo

CodePudding user response:

The simple way in C 17 is to use static_assert

#include <type_traits>

template<auto first, auto... rest> 
struct Custom {
  static_assert(
    (std::is_same_v<decltype(first), decltype(rest)> && ...),
  "non-type template parameter pack must be the same type.");
};

In C 20, you can just use concepts:

#include <concepts>

template<auto first, auto... rest> 
  requires (std::same_as<decltype(first), decltype(rest)> && ...)
struct Custom {
  
};
  • Related