以下两种语法有什么区别:
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;
const A*
不是 A*
的 const
限定版本,而是一个不相关的类型。A* const
才是 A*
的 const
限定版本。 - CB Bailey
typename
参数类型吗?(请参见我的答案)。我无法访问标准,而且在我手头的草案中很难找到有用的信息。 - J.N.const typename
:P)。 - Xeo