运算符() 重载和函数对象中的 c'tor 歧义
operator() overload and c'tor ambiguity in function objects
假设我们有下一个函数对象:
class foo{
private:
int counter;
public:
foo(int counter): counter(counter){}
foo& operator=(const foo& ){...}
bool operator() (int variable){....}
}
int main(){
foo f(4);
foo x(5);
x = f(4);
return 0;
}
编译器如何知道如何响应:x = f(5)
吗?我已经在网上和Stack上搜索了一段时间,还没有找到确切的答案,如果是转发,告诉我,我会删除这个问题。
这取决于"(5)"是用来构造一个对象还是在一个已经存在的对象上调用:
foo f(5); // calls the constructor
f(5); // calls operator()
我添加了一个叫做eval
的简单方法来解释它:
class foo {
private:
int counter;
public:
foo(int counter): counter(counter) {}
bool operator() (int variable) {
return variable < counter;
}
bool eval(int variable) {
return variable < counter;
}
};
-
foo
是类而不是方法。 -
foo
的实例可以像方法一样使用。 调用
foo(5)
将创建一个foo
的实例,其中counter = 5
.eval
是foo
的成员函数。(现在它的作用与()
操作符相同)
你可以这样调用eval
:
foo f = foo(5); // create an instance of `foo`
f.eval(3); // returns true -> 3 < 5
f.eval(0); // returns false -> 6 < 5
也可以使用()
运算符:
foo f = foo(5); // create an instance of `foo`
f(3); // returns true -> 3 < 5
f(0); // returns false -> 6 < 5
注意:
你也可以这样写(但不要这样做):
foo f = foo(5); // create an instance of `foo`
f.operator()(3); // returns true -> 3 < 5
f.operator()(0); // returns false -> 6 < 5
相关文章:
- 构造对象的歧义
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 我叫删除,但我的d-tor没有叫,为什么?
- 数组初始值设定项的构造函数歧义
- 为共享 ptr 向量实现复制 c'tor?
- 消除好友和成员二进制运算符的歧义
- 使用共享指针实现复制 c'tor?
- 用' . '代替' :: '会在C++中造成歧义吗?
- 为什么下面带有非常量转换函数的代码没有歧义?
- 通过 Tor 服务C++ socket.io 客户端
- std::p ackaged_task 应该删除带有 const 参数的复制 c'tor
- std::bind 是否实现了 std::ref 和 std::cref 来消除函数调用的歧义?
- C++复制 c'tor 现在确实会采取行动。 不清楚为什么
- 使用 bool 和 const char 重载的 C++ 函数会在没有警告的情况下产生歧义 (MSVC2012)
- C++SFINAE enable_if_t成员函数,如何消除歧义?
- 多重继承相同的方法名,没有歧义
- 如何在模板化转换运算符中消除此构造的歧义?
- 当存在覆盖歧义函数时,代码如何运行?
- 如何区分宏函数和函数函数而没有任何歧义?
- 运算符() 重载和函数对象中的 c'tor 歧义