Is there any difference between following 2 syntax:
template<int N> struct A; // (1)
and
template<const int N> struct A; // (2)
Any general guideline for when to use each syntax ?
Is there any difference between following 2 syntax:
template<int N> struct A; // (1)
and
template<const int N> struct A; // (2)
Any general guideline for when to use each syntax ?
No.
§14.1 [temp.param] p5
[...] The top-level cv-qualifiers on the template-parameter are ignored when determining its type.
typename
parameter kind only ? (See my answer). I do not have access to the standard and I am rather bad at finding useful information in the draft I have.
– J.N.
Mar 13 '12 at 6:25
const typename
anyways :P).
– Xeo
Mar 13 '12 at 6:26
const
is not useful in any case, your answer just talks about the comparison between them. It's worth mentioning when to use which version (i.e. always use 1st). It's your wish :). This is just for reference for the future/novice visitors.
– iammilind
Mar 14 '12 at 3:13
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
.
The choice of int
was probably a bad idea, it makes a difference for pointers though:
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*
is not the const
qualified version of A*
. It is an unrelated type. A* const
is the const
qualified version of A*
.
– CB Bailey
Mar 13 '12 at 6:51