jeudi 1 décembre 2016

Do I need T&& and std::forward when writing a templated `<<` operator?

I'm writing a class which is meant to be used like MyClass() << "some args here" << ...; and forwards these values to a regular ostream that it holds internally.

This seems to work:

class MyClass {
    std::ostringstream oss;

public:
    template<typename T>
    MyClass& operator<<(T&& val) {
        oss << std::forward<T>(val);
        return *this;
    }
    ~MyClass() {
        std::cout << "Final result: " << oss.str() << std::endl;
    }
};

I used T&& and std::forward<T> because I'm used to seeing them with perfect forwarding.

However, this works too:

template<typename T>
MyClass& operator<<(T val) {
    oss << val;
    return *this;
}

So is the "perfect forwarding" actually necessary? I wasn't able to construct a counterexample for the simplified version, no matter whether the available operator<< for T takes it by value or by reference.

Aucun commentaire:

Enregistrer un commentaire