将std::forward作为默认参数传递

Passing std::forward as a default argument?

本文关键字:默认 参数传递 forward std      更新时间:2023-10-16

考虑以下以函数为实参的函数:

template <class Function = std::plus<int> > 
void apply(Function&& f = Function());

这里std::plus<int>是应用的默认函数。std::plus<int>是一个函数对象,并且都运行良好。

现在,我想传递std::forward<int>作为默认参数。std::forward<int>不是一个函数对象,这是一个函数指针。怎么做?

template <class Function = /* SOMETHING */ > 
void apply(Function&& f = /* SOMETHING */);

指向std::forward<int>的函数指针类型为int &&(*)(int &)。所以你的函数应该是这样的:

template<class T = int &&(*)(int &)>
void apply(T &&t = &std::forward<int>);

看一下std::forward是如何声明的:http://en.cppreference.com/w/cpp/utility/forward

我认为这将工作:

template <class Function = decltype(&std::forward<int>)> 
void apply(Function&& f = &std::forward<int>);

编辑:实际上,也许不是。你最好重载它:

void apply() {
  apply(&std::forward);
}