Considering Scott Meyer's book, Effective Modern C ++, paragraph 24 (and later) and paragraph 41, I am curious that this book contradicts:
- individual constructors for lvalue and rvalue parameters
to
- generic universal design solution
It says that 1. has the disadvantage of duplicating code.
While 2. has a flaw potentially used for unwanted types.
I wonder why the book does not mention a mixed model , as in the code example below.
It uses specialized constructors with type support for lvalue and rvalue, but it delegates one (private) common implementation for a "universal reference". This avoids the unwanted template types of the public universal link constructor.
So, is there something wrong with the approach below? Did I miss something?
#include <iostream>
#include <string>
class MyClass
{
private:
enum class Dummy { Nop = 0 } ;
template <class T>
MyClass(Dummy, T&& data)
: _data(std::forward<T>(data))
{
std::cout << "MyClass universal reference template c'tor" << std::endl;
}
public:
MyClass (std::string const & data)
: MyClass(Dummy::Nop, data)
{
std::cout << "MyClass lvalue c'tor" << std::endl;
}
MyClass (std::string && data)
: MyClass(Dummy::Nop, std::move(data))
{
std::cout << "MyClass rvalue c'tor" << std::endl;
}
private:
std::string _data;
};
int main(int, char**)
{
{
std::string str("demo");
MyClass myClass(str);
}
{
MyClass myClass("hello, world");
}
return 0;
}
source
share