【问题标题】:const in template argument [duplicate]模板参数中的 const [重复]
【发布时间】:2012-11-06 06:41:46
【问题描述】:

这个模板中const关键字的作用是什么?

template <class T, int const ROWNUM, int const COLNUM> 
class Matrix

这是否意味着这个模板只接受const 作为参数?如果是这样,有没有办法将变量作为COLNUMROWNUM 传递?

(当我尝试将变量作为模板的 COLNUM 传递时,它会给出错误:“IntelliSense:表达式必须具有常量值”)

【问题讨论】:

    标签: c++ templates constants


    【解决方案1】:

    const 在您的情况下不需要

    例如,对于编译器观点,下面的Matrix_AMatrix_B 两个类都是相同的。 const 只是为了强制执行以下事实:ROWNUMCOLNUM 对于人类观点来说是恒定的,但不是必需的。

    template <class T, int const ROWNUM, int const COLNUM> 
    class Matrix_A 
    {
    };
    
    template <class T, int       ROWNUM, int       COLNUM> 
    class Matrix_B
    {
    };
    

    此外,Matrix_C 类还以另一种方式指定了类似的常量变量ROWNUMCOLNUM

    template <class T> 
    class Matrix_C
    {
       static int const ROWNUM = 5;
       static int const COLNUM = 20;
    };
    
    // the following three objects use constant variables ROWNUM and COLNUM
    Matrix_A<bool,5,20> a;
    Matrix_B<bool,5,20> b;
    Matrix_C<bool>      c;
    

    【讨论】:

    【解决方案2】:

    它被忽略了:

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

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

    [C++11: 14.1/5]: [ 注意: 其他类型要么在下面明确地被禁止,要么被管理 template-arguments (14.3) 形式的规则隐含地禁止。 —结束注释 ] 在确定其类型时,模板参数上的顶级cv-qualifiers被忽略 .

    相同的措辞出现在 C++03 中的相同位置。

    这部分是因为模板参数必须在编译时知道。所以,不管你有没有constyou may not pass some variable value

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

    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: 错误:需要左值作为赋值的左操作数

    【讨论】:

    • 这很奇怪,因为当我尝试将变量作为模板的 COLNUM 传递时,它会给出错误:“IntelliSense:表达式必须具有常量值”
    • @Chin:为什么这么奇怪?模板参数必须在编译时知道,因为那是扩展模板的时候。
    • 我明白了。那么有没有办法在运行时做到这一点?
    • @Chin:当然——只需使用普通函数参数即可。也许是类构造函数的参数。
    • @Yakk: Pfft :P BTW 第 44 行看起来不正确(如 here 所示)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 2016-05-23
    • 2011-08-25
    • 2021-09-02
    • 2010-11-01
    • 1970-01-01
    相关资源
    最近更新 更多