mardi 27 décembre 2016

How to avoid writing std::reference_wrapper version template all the time?

I have a function template to echo something from the class, for example:

template<typename T>
void say(const std::vector<T>& ts)
{
    for (const auto& t : ts) {
        std::cout<<t.getDesc()<<std::endl;
    }
}

class Base
{
public
    Base();
    const std::string& getDesc() const {
        return m_desc;
    }
protected:
    std::string m_desc;
}

All objects inherited from Base can use the template function.

std::vector<Base> v;
Base a;
v.push_back(a)

But when I turn to std::reference_wrapper, the function template does not work. I should write another template to fix it.

template<typename T>
void say(const std::vector<std::reference_wrapper<T>>& ts)
{
    for (const auto& t : ts) {
        std::cout<<t.get().getDesc()<<std::endl;
    }
}

The only difference between them is the std::reference_wrapper::get().

So is there any other way to avoid this annoying code? Or should I write std::reference_wrapper version template for all the function I used?

Aucun commentaire:

Enregistrer un commentaire