dimanche 26 novembre 2017

How to make const only lvalue in a constructor with std::forward

template < typename T1, typename T2 >
MyClass(T1 && v1, T2 && v2)
    : m_v1(std::forward< T1 >(v1))
    , m_v2(std::forward< T2 >(v2))
{}

Let us have a class, named MyClass, its constructor showed above. In case without std::forward we have to write 4 different constructors:

MyClass(SomeType&& v1, SomeType&& v2);
MyClass(SomeType&& v1, const SomeType& v2);
MyClass(const SomeType& v1, SomeType&& v2);
MyClass(const SomeType& v1, const SomeType& v2);

Here we use const SomeType&, because we don’t want to change our lvalue. Of course, we have const_cast, but it’s easy to find such cast. The same time, our template constructor with std::forward generates constructors with argument type smth like this: SomeType& - without const and therefore we can change the lvalue in the body of our constructor.

Question: What is the correct solution? Should I add const (how to do it?) or just write the body of my constructors in a proper way - so, they won’t change the lvalue. In case with adding const we will get smth like this: const T1&& and if we give rvalue to constructor, we can’t move it, because it will be constant rvalue. I suppose, that we have to add const only if we give lvalue.

Aucun commentaire:

Enregistrer un commentaire