How to define a nested template

Viewed 69

I defined a function as below, which took an integer as a template parameter, it worked as expected.

template<int D, typename std::enable_if<std::greater<int>{}(D, 100), void*>::type = nullptr>
void func(int p) {
    // something
}
func<100>(1); // ERROR
func<101>(1); // OK

Now, I want to make the int as a template parameter too. Meaning that I need something like this:

template<T D, typename std::enable_if<std::greater<T>{}(D, 100), void*>::type = nullptr>
void func(int p) {
    // something
}

Well, I've tried as below but it's not compilable.

template<typename T, template<T D, typename std::enable_if<std::greater<T>{}(D, 100), void*>::type = nullptr>>
void func2(int p) {
    // something
}
2 Answers

You need to declare T as type template parameter firstly. E.g.

template<typename T, T D, typename std::enable_if<std::greater<T>{}(D, 100), void*>::type = nullptr>
void func(int p) {
    // something
}

then

func<int, 100>(1); // ERROR
func<int, 101>(1); // OK

If you don't want to specify int explicitly, you can

template<auto D, typename std::enable_if<std::greater<>{}(D, 100), void*>::type = nullptr>
void func(int p) {
    // something
}

then

func<100>(1); // ERROR
func<101>(1); // OK

If you have access to C++17, use auto non-type template parameter:

template<auto D, typename std::enable_if<std::greater<>{}(D, 100), void*>::type = nullptr>
void func(int p) {
    // something
}
Related