【发布时间】:2012-03-29 13:31:39
【问题描述】:
以下两种语法有什么区别:
template<int N> struct A; // (1)
和
template<const int N> struct A; // (2)
关于何时使用每种语法的任何一般准则?
【问题讨论】:
标签: c++ templates syntax constants
以下两种语法有什么区别:
template<int N> struct A; // (1)
和
template<const int N> struct A; // (2)
关于何时使用每种语法的任何一般准则?
【问题讨论】:
标签: c++ templates syntax constants
没有。
§14.1 [temp.param] p5
[...] template-parameter 上的顶级 cv-qualifiers 在确定其类型时会被忽略。
【讨论】:
typename 参数种类吗? (见我的回答)。我无法访问该标准,而且在我的草稿中找到有用信息方面相当糟糕。
const typename:P)。
const 在任何 情况下都没有用,但您的回答只是谈论它们之间的比较。值得一提的是何时使用哪个版本(即始终使用 1st)。这是你的愿望:)。仅供未来/新手访问者参考。
我发现这是在快速搜索标准:
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* 不是const 的合格版本A*。它是一种不相关的类型。 A* const 是const 的合格版本A*。