0

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.

111111
  • 15,686
  • 6
  • 47
  • 62

1 Answers1

3

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&.

Barry
  • 286,269
  • 29
  • 621
  • 977
  • I'll check the callsites, but I don't think any of them explicitly specify the type. I get similar errors with both clang and gcc so I am quite sure it's my code that's wrong. – 111111 Nov 09 '20 at 23:01
  • 5
    @111111 That's why we ask for [mcve] in [ask]. – Barry Nov 09 '20 at 23:02
  • @Barry hard to guess what op problem was, but one common case when type is deduced to be reference is a when argument to function is universal/forwarding reference, possible that source in question is not properly reduced from real code... – NoSenseEtAl Nov 11 '20 at 12:38