完美转发到数据成员的成员函数? [英] Perfect forwarding to a member function of a data member?

查看:138
本文介绍了完美转发到数据成员的成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个具有私人 std :: vector 数据成员的类:

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

语法正确(使用C ++ 14 auto / variadic templates / forward ...)将 _data 的给定函数传递到 MyClass (例如 insert $ p $ b
$ b

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

但是,你实际上不需要C ++ 14。您只需使用C ++ 11语法。

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


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?

解决方案

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)...);
        }
};

这篇关于完美转发到数据成员的成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆