constant references with typedef and templates in c++

This:

typedef int& ref;
const ref error;

Doesn’t do what you think it does. Consider instead:

typedef int* pointer;
typedef const pointer const_pointer;

The type of const_pointer is int* const, not const int *. That is, when you say const T you’re saying “make a type where T is immutable”; so in the previous example, the pointer (not the pointee) is made immutable.

References cannot be made const or volatile. This:

int& const x;

is meaningless, so adding cv-qualifiers to references has no effect.

Therefore, error has the type int&. You cannot assign a const int& to it.


There are other problems in your code. For example, this is certainly wrong:

template<class t>
t const& check()
{
    return t(); //return a temporary object
}

What you’re doing here is returning a reference to a temporary object which ends its lifetime when the function returns. That is, you get undefined behavior if you use it because there is no object at the referand. This is no better than:

template<class t>
t const& check()
{
    T x = T();
    return x; // return a local...bang you're dead
}    

A better test would be:

template<class T>
T check()
{
    return T();
}

The return value of the function is a temporary, so you can still test that you can indeed bind temporaries to constant references.

Leave a Comment