c++ - 什么样的值是模板参数?我能(不能)用它们做什么?

标签 c++ templates value-categories

可以将值分配给模板非类型参数吗?

例如

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/

相关文章:

c++ - 为什么这个简单的 enable_if 不起作用?

c++ - 右值、左值和正式定义

c++ - 为什么 std::move() 在 C++ 中工作?

c++ - 将单个 C++ 程序分解为具有继承性的多文件程序

c++ - 使用dumpbin查看C++库信息时,UNDEF和notype()是什么意思?

c++ - 是否有从其他模板参数推导出来的强制模板参数之类的东西?

c++ - decltype-specifier 表示的类型是什么类型,其表达式是类类型的临时对象的成员?

c++ - cudaDeviceSynchronize() 错误代码 77 : cudaErrorIllegalAddress

c++ - 查看窗口是否有菜单栏

c++ - 在 C++ 中,如何在不使用 new 且不单独声明单个元素的情况下创建 `std::initializer_list<base *>`?