【发布时间】:2017-10-01 02:12:10
【问题描述】:
我想编写一个函数foo,它应该调用其参数的operator(),如下面的(损坏的)代码所示:
template <typename T> void foo(const T& x){
x();
}
struct MyFunctor{
int data;
void operator()(){
/* stuff that might modify the data */
}
};
int main()
{
foo(MyFunctor{});
}
显然代码不起作用,因为operator() 不是const,但foo() 要求其参数为const。
作为模板函数,foo() 应该与const 和非const 函子一起使用,并且不要对其参数的const-ness 挑剔。
如果我通过删除 const 来更改 foo() 为以下内容:
template <typename T> void foo(T& x) { /* ... */ }
...它也不起作用,因为您无法将右值引用转换为非const 左值引用,因此无法调用foo(MyFunctor{})。
将foo() 更改为转发引用可以解决所有问题:
template <typename T> void foo(T&& x) { /* ... */ }
但这是“正确”的方式吗?转发引用不应该只与std::forward() 一起使用(即除了将其转发到另一个函数之外,不应触及该参数)?
【问题讨论】:
-
您可能想阅读Universal References in C++11—Scott Meyers。其中包含对
T&& x使用的一些深入解释。 -
这很好,IMO
-
我很荣幸有六位数声誉的人回答我的问题!
-
我相信这就是他们获得六位数声誉的方式。
标签: c++ c++11 templates constants forwarding-reference