模板参数中的const

Chi*_*hin 17 c++ templates const

const关键字在此模板中的作用是什么?

template <class T, int const ROWNUM, int const COLNUM> 
class Matrix
Run Code Online (Sandbox Code Playgroud)

这是否意味着此模板仅接受constas参数?如果是这样,有没有办法将变量作为COLNUMROWNUM

(当我尝试将变量作为模板的COLNUM传递时,它会出错:"IntelliSense:expression必须具有常量值")

Lig*_*ica 20

它被忽略了:

[C++11: 14.1/4]:非类型模板参数应具有以下之一(可选的cv限定)类型:

  • 积分或枚举类型,
  • 指向对象或指向函数的指针,
  • 左值引用对象或左值引用函数,
  • 指向成员的指针,
  • std::nullptr_t.

[C++11: 14.1/5]:[ 注意:管理模板参数形式的规则明确地禁止或隐式地禁止其他类型(14.3).-end note ] 确定模板参数的类型时,将忽略template-parameter上的顶级cv限定符.

在C++ 03中的相同位置存在相同的措辞.

这部分是因为无论如何必须在编译时知道模板参数.所以,无论你是否有const,可能不会传递一些变量值:

template <int N>
void f()
{
    N = 42;
}

template <int const N>
void g()
{
    N = 42;
}

int main()
{
    f<0>();
    g<0>();

    static const int h = 1;
    f<h>();
    g<h>();
}
Run Code Online (Sandbox Code Playgroud)

prog.cpp:在函数' void f()[with int N = 0] ':
prog.cpp:15:从这里实例化
prog.cpp:4:错误:左值作为赋值的左操作数
prog.cpp:在函数中' void g()[with int N = 0] ':
prog.cpp:16:从这里实例化
prog.cpp:10:错误:左值作为赋值的左操作数
prog.cpp:在函数' void f()[ with int N = 1] ':
prog.cpp:19:从这里实例化
prog.cpp:4:错误:左值作为赋值的左操作数
prog.cpp:在函数' void g()[with int N = 1] ':
prog.cpp:20:从这里实例化
prog.cpp:10:错误:左值作为赋值的左操作数需要左值