可以将值分配给模板非类型参数吗?
例如
template<int N>
void foo(){
N = 4;
}
尝试编译我得到:
error: lvalue required as left operand of assignment
N = 4;
^
什么样的值(Value Category)是模板参数,我可以在函数体中“玩弄”多少? (即读取它们、写入它们、将它们转发给其他模板参数、打印它们等)。
例如,创建“注册”一个数字(在编译时作为模板参数传递)然后在每次调用时(在运行时)打印该数字的函数模板的正确方法是什么?
最佳答案
它们大致等同于具有给定值的文字。在 C++20 中有一个概念 LiteralType
,这是成为非类型模板参数的要求。
来自 cppreference
When the name of a non-type template parameter is used in an expression within the body of the class template, it is an unmodifiable prvalue unless its type was an lvalue reference type
来自 the standard
A non-type non-reference template-parameter is a prvalue. It shall not be assigned to or in any other way have its value changed. A non-type non-reference template-parameter cannot have its address taken. When a non-type non-reference template-parameter is used as an initializer for a reference, a temporary is always used.
关于c++ - 什么样的值是模板参数?我能(不能)用它们做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55835025/