admin管理员组

文章数量:1122846

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?

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?

Share Improve this question asked Nov 22, 2024 at 13:59 AlexAlex 12 bronze badges 4
  • 2 This looks like an XY problem. Why do you want to do this? – molbdnilo Commented Nov 22, 2024 at 14:05
  • 1 If the instantiation of a template causes a difference in behaviour somewhere else, your design is incorrect. – Passer By Commented Nov 22, 2024 at 14:22
  • I definitely got into an XY problem. need to ask differently – Alex Commented Nov 22, 2024 at 14:26
  • what would the error be good for? what would happen is someone does not instantiate it? – 463035818_is_not_an_ai Commented Nov 22, 2024 at 16:42
Add a comment  | 

1 Answer 1

Reset to default -1

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>();
}

本文标签: chow do force the programmer to instantiate a templateStack Overflow