模板参数中“T”和“const T”之间有什么区别吗?

时间:2012-03-13 06:05:32

标签: c++ templates syntax const

以下2种语法之间是否有任何区别:

template<int N> struct A;         // (1)

template<const int N> struct A;   // (2)

何时使用每种语法的一般准则?

3 个答案:

答案 0 :(得分:27)

没有

§14.1 [temp.param] p5

  

[...] template-parameter 上的顶级 cv-qualifiers 在确定其类型时会被忽略。

答案 1 :(得分:5)

我发现这可以快速搜索标准:

template<const short cs> class B { };
template<short s> void g(B<s>);
void k2() {
    B<1> b;
    g(b); // OK: cv-qualifiers are ignored on template parameter types
}

评论说他们被忽略了。

我建议不要在模板参数中使用const,因为这是不必要的。请注意,它也不是“暗示” - 它们是与const不同的常量表达式。

答案 2 :(得分:2)

选择int可能是一个坏主意,但它对指针有所不同:

class A
{
public:
    int Counter;
};

A a;


template <A* a>
struct Coin
{
    static void DoStuff()
    {
        ++a->Counter; // won't compile if using const A* !!
    }
};

Coin<&a>::DoStuff();
cout << a.Counter << endl;
相关问题