C++ const reference template function argument type is itself a reference, why?

627 Views Asked by At

I have the following function:

template<typename T>
void f(const T& val) {
    using value_type = T;
    using sub_type = typename value_type::sub_type;
    //etc...
}

However, I am running into the problem that the compiler is telling me that T is not fact whatever type it is, but instead a reference to it. How is that possible, in what circumstances are template parameter for const-references themselves references?

Note, I can work around the above issue with:

    using value_type = std::remove_reference_t<T>;

but I'd like to understand what circumstances T, itself, would be a reference.

1

There are 1 best solutions below

3
Barry On

How is that possible, in what circumstances are template parameter for const-references themselves references?

These things are independent. We have a template parameter, T. And then we a have a function parameter that happens to be T const&. But the two aren't tied together.

While T would never be deduced to a reference type based on that function parameter, deduction isn't the only way to provide template parameters:

template <typename T>
void f(T const& val);

void g(int i) {
    f<int&>(i);
}

Here, I am explicitly providing int& as the template argument for T, it is not deduced. T, here, would be int& (not int) and indeed val isn't even a reference to const here, it would actually be an int& (not a int const&).

Of course the typical usage would be just f(i) (no explicit template arguments) which would deduce T as int and have val be of type int const&.