iammilind
iammilind

Reputation: 69988

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 ?

Upvotes: 43

Views: 4746

Answers (3)

J.N.
J.N.

Reputation: 8421

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;

Upvotes: 2

Pubby
Pubby

Reputation: 53047

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.

Upvotes: 8

Xeo
Xeo

Reputation: 131799

No.

§14.1 [temp.param] p5

[...] The top-level cv-qualifiers on the template-parameter are ignored when determining its type.

Upvotes: 36

Related Questions