I thought universal reference (T&&
) is supposed to take any kind of reference. But the following doesn't work.
I run into this problem when I try to be const-correct in a library that I am writing. I am new to C++ and haven't seen something like this before.
test.cpp:
enum Cv_qualifier {
constant,
non_const
};
template <Cv_qualifier Cv> class A;
template<>
class A<Cv_qualifier::constant> {
public:
template<Cv_qualifier Cv2>
void t(const A<Cv2>&& out) {}
};
template <>
class A<Cv_qualifier::non_const> {
public:
template<Cv_qualifier Cv2>
void t(const A<Cv2>&& out) {}
};
int main()
{
A<Cv_qualifier::non_const> a;
A<Cv_qualifier::constant> b;
a.t(b);
}
Error (compiled with g++ test.cpp -std=c++11
):
test.cpp: In function ‘int main()’:
test.cpp:24:10: error: cannot bind ‘A<(Cv_qualifier)0u>’ lvalue to ‘const A<(Cv_qualifier)0u>&&’
a.t(b);
^
test.cpp:17:10: note: initializing argument 1 of ‘void A<(Cv_qualifier)1u>::t(const A<Cv2>&&) [with Cv_qualifier Cv2 = (Cv_qualifier)0u]’
void t(const A<Cv2>&& out) {}
^
By the way, in the actual program, the class A
does not own any actual data, and contain references to another class that actually hold the data. I hope this means I am not constantly create indirection/copy data when I allow the member function t
of class A
to accept temporary objects.
std::vector<T>&&
orclass_name<Template parameters>&&
are not universal references? And the only way to write a universal reference isT&&
? I thought theCv_2
template parameter of thet
member function has to be deduced. – DrydenT&&
is the only way to make an argument that accepts both l-value and r-value references. – DrydenT&&
is not the only way for a function to accept l-value and r-values. In your case all you need to do is acceptA<Cv2> const&
and it'll accept anything. – CollusionT&&
,andT
is a template parameter of the function – OutlawA<Cv2> const& a
prevent modification of the values of a? ok I get it. So it does limit modification of the values of a. it is a constant reference. #3695130 – Dryden