可能重复:
使用forward的优点
我知道它的作用以及何时使用它但我仍然无法理解其工作原理.请尽可能详细,并解释std::forward如果允许使用模板参数推断,何时不正确.
我的一部分困惑是:"如果它有一个名字,它就是一个左值" - 如果是这样的话,为什么std::forward当我通过thing&& xvs 时表现不同thing& x?
这是这个问题的后续内容,我鼓励在可变参数模板operator()(...)实现中使用完美转发.这是我的观察者模式,我想用它来调用具有可变参数的自由函数和成员函数:
#ifndef _SIGNALS_H_
#define _SIGNALS_H_
#include <utility>
/** Interface for delegates with a specific set of arguments **/
template<typename... args>
class AbstractDelegate
{
public:
virtual void operator()(args&&...) const = 0;
virtual ~AbstractDelegate() {}
};
/** Concrete function delegate that discards the function's return value **/
template<typename ReturnType, typename... args>
class FnDelegate : public AbstractDelegate<args...>
{
public:
/** member function typedef **/
using Fn = ReturnType(*)(args...);
/** constructor **/
FnDelegate(Fn fn)
: fn_{fn}
{
}
/** call operator that …Run Code Online (Sandbox Code Playgroud)