Baker-xie
Baker-xie

Reputation: 1

why const before template parameter does not work

I'm so confused why the following code doesn't work?

The compiler says: error: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’ 6 | const T a = 1;

template<typename T>
void f(T&& t)
{
    const T a = 1;
}

int main()
{
    int i;
    int& k = i;
    f(k);
}

Upvotes: 0

Views: 70

Answers (2)

Guillaume Racicot
Guillaume Racicot

Reputation: 41840

To add to the other response, you can easily see that if you're using east const style:

template<typename T>
void f(T&& t)
{
    T const a = 1;
}

Now, the compiler would instantiate into something that looks like this:

template<>
void f(int& t) {
    int& const a = 1;
}

The const keywords always applies to the thing on its left, unless there is none.

It applies on the whole reference, but references can't be changed in C++ so it doesn't change anything!

So this is pretty much equivalent to:

template<>
void f(int& t) {
    int& a = 1;
}

Which as the other answers says, invalid.

Upvotes: 1

Jarod42
Jarod42

Reputation: 218268

with f(k); we call template<typename T> void f(T&& t) with T = int&.

const T is not const int& (nor int const&) but int& (as const applied to reference is useless).

and

int& a = 1; is invalid.

Upvotes: 3

Related Questions