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
1 Answer
Reset to default -1The 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
版权声明:本文标题:c++ - how do force the programmer to instantiate a template? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736303284a1931831.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论