Is there any difference between "T" and "const T" in template parameter?
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 ?
Solution 1:
No.
§14.1 [temp.param] p5
[...] The top-level cv-qualifiers on the template-parameter are ignored when determining its type.
Solution 2:
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
.
Solution 3:
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;