模板参数中的"T"和"const T"有什么区别吗?

Is there any difference between "T" and "const T" in template parameter?

本文关键字:什么 区别 const 参数      更新时间:2023-10-16

以下两种语法之间有什么区别吗:

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

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

关于何时使用每种语法,有什么通用指南吗?

否。

§14.1 [temp.param] p5

[…]在确定其类型时,会忽略模板参数上的顶级cv限定符

我在快速搜索标准时发现了这一点:

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不同。

选择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;