Is there any difference between following 2 syntax:
以下2种语法之间有什么区别:
template<int N> struct A; // (1)
and
和
template<const int N> struct A; // (2)
Any general guideline for when to use each syntax ?
何时使用每种语法的一般准则?
3 个解决方案
#1
24
No.
没有。
§14.1 [temp.param] p5
§14.1[temp.param] p5
[...] The top-level cv-qualifiers on the template-parameter are ignored when determining its type.
[...]模板参数的*cv限定符在确定其类型时会被忽略。
#2
5
I found this doing a quick search of the standard:
我发现这样可以快速搜索标准:
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
}
The comment says they are ignored.
评论说他们被忽略了。
I'll recommend not using const
in template parameters as it's unnecessary. Note that it's not 'implied' either - they're constant expressions which is different from const
.
我建议不要在模板参数中使用const,因为它是不必要的。请注意,它也不是“暗示” - 它们是与const不同的常量表达式。
#3
2
The choice of int
was probably a bad idea, it makes a difference for pointers though:
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;
#1
24
No.
没有。
§14.1 [temp.param] p5
§14.1[temp.param] p5
[...] The top-level cv-qualifiers on the template-parameter are ignored when determining its type.
[...]模板参数的*cv限定符在确定其类型时会被忽略。
#2
5
I found this doing a quick search of the standard:
我发现这样可以快速搜索标准:
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
}
The comment says they are ignored.
评论说他们被忽略了。
I'll recommend not using const
in template parameters as it's unnecessary. Note that it's not 'implied' either - they're constant expressions which is different from const
.
我建议不要在模板参数中使用const,因为它是不必要的。请注意,它也不是“暗示” - 它们是与const不同的常量表达式。
#3
2
The choice of int
was probably a bad idea, it makes a difference for pointers though:
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;