Vincent Vincent - 4 months ago 17
C++ Question

Perfect forwarding to a member function of a data member?

Consider a class that has a

private
std::vector
data member:

class MyClass
{
private:
std::vector<double> _data;
public:
template <class... Args>
/* something */ insert(Args&&... args) /* something */
{
return _data.insert(std::forward<Args>(args)...);
}
};


What is the correct syntax (using C++14 auto/variadic templates/forward...) to transfer a given function of
_data
to
MyClass
(for example
insert
here) and provide the same interface for the user?

Answer

The correct syntax is this:

class MyClass 
{
    private: 
        std::vector<double> _data;
    public:
        template <class... Args>
        decltype(auto) insert(Args&&... args)
        {
            return _data.insert(std::forward<Args>(args)...);
        }
};

However, you don't actually need C++14 to do it. You can just use the C++11 syntax.

class MyClass 
{
    private: 
        std::vector<double> _data;
    public:
        template <class... Args>
        auto insert(Args&&... args) 
        -> decltype(_data.insert(std::forward<Args>(args)...))
        {
            return _data.insert(std::forward<Args>(args)...);
        }
};
Comments