Alex
Alex

Reputation: 1

how do force the programmer to instantiate a template?

Here is some template constexpr function.

template <class> constexpr void function();

I want to force the programmer to instantiate function with a specific template parameter.

template void function<int>(); // the program is well-formed

If the programmer didn't do this, I want a compile-time error.

How to achieve this?

Upvotes: 0

Views: 98

Answers (1)

Alexey S. Larionov
Alexey S. Larionov

Reputation: 7937

The simplest example is using static_assert, so that invalid templates cannot be instantiated (thus compiled):

#include <type_traits>

template <class T> constexpr void function() {
    static_assert(std::is_same_v<T, int>);
    // ... function implementation
}

int main() {
    function<int>();
    //function<unsigned int>();
    //function<float>();
}

Upvotes: -1

Related Questions