I am building a template class that must be able to hold a value or a reference.
I am building the library for C++11 compatibility.
Here is the relevant code for the class
template<typename T>
class Foo
{
private:
T _Data;
public:
Foo(const T& i_Data) :
_Data(i_Data)
{}
virtual ~Foo()
{}
Foo(const Foo &i_Other):
_Data(i_Other._Data)
{};
Foo(Foo &&io_Other):
_Data(std::move(io_Other._Data))
{}
// etc..
};
The code works excepted when creating a Foo object in this way:
double Bar = 2.5;
Foo<double&> f = Bar; // This does not compile (in c++11, C++20 works though)
// error: cannot bind non-const lvalue reference of type ‘double&’ to an rvalue of type ‘std::remove_reference<double&>::type’ {aka ‘double’}
Foo<double&> f(Bar); // This does compile
I figured that when using the first line, the compiler tries to build a temporary Foo, and then move this into the Foo, although i don’t understand why and how to cleanly avoid this (Of course, i could remove the move constructor but that’s a cheesy fix)
Also, why does it work with C++20 and not C++11. From what i can see this is not a problem related to template deduction so this should work the same in both standards right?