【发布时间】:2021-02-07 04:07:19
【问题描述】:
我想知道,为什么 c++ 中的函数对象被实现为模板化,而自 c++14 以来,void 是默认类型。
例如:
- https://en.cppreference.com/w/cpp/utility/functional/plus
- https://en.cppreference.com/w/cpp/utility/functional/minus
当被operator()调用时,这个对象实际上执行算术运算+、-、*、/。
operator() 必须是模板才能使用不同的类型作为参数,但为什么必须是结构?
编辑
我可以创建一个运算符std::plus<>,它可能适用于operator() 中的不同类型:
struct Foo{
int foo;
};
Foo operator+(const Foo& lhs, const Foo& rhs){
return {2 * lhs.foo + 3 * rhs.foo};
}
std::ostream& operator<<(std::ostream& os, const Foo& f){
std::cout << f.foo;
return os;
}
int main()
{
auto op = std::plus<>();
std::cout << op(5, 3) << "\n";
std::cout << op(3.14, 2.71) << "\n";
std::cout << op(Foo(2), Foo(3)) << "\n";
}
这给出了预期的输出。或者可能是这样,在最初指定类型后,您会得到更优化的东西?
【问题讨论】:
标签: c++ operators arithmetic-expressions