C++获取重载成员运算符函数指针地址

有如下语句:


class CTestObject
{
public:
	bool operator()(int, int, float) const
	{
		return false;
	}

	bool operator( )(int, float)
	{
		return false;
	}
};

void Test( )
{
	CTestObject obj;
	std::function f;
    
	f = obj; // 正确
	f = std::bind(&CTestObject::operator(),&f); //编译推断失败
	f = std::bind(&CTestObject::operator(), &f,
		std::placeholders::_1, std::placeholders::_2, .0f); // 编译推断失败

	f = std::bind(&CTestObject::operator()(int,float), &f); //语法错误
	f = std::bind(&CTestObject::operator()(int,float,float), &f,
		std::placeholders::_1, std::placeholders::_2, .0f); //语法错误
}

上述错误有一个共同点,std::bind自身需要根据参数推断类型。无法根据不确定的类型推断出std::bind自身。很明显也不满足下面的7)。

c++语言标准给出的重载适用场合:

Besides function-call expressions, where overload resolution takes place, the name of an overloaded function may appear in the following 7 contexts(除了函数调用外,重载函数名还可出现在下列种上下文情景中):

1) initializer in a declaration of an object or reference (对象或引用声明初始化)
2) on the right-hand-side of an assignment expression (赋值表达式右侧)
3) as a function call argument (作为函数调用的参数)
4) as a user-defined operator argument (作为用户自定义运算符参数)
5) the return statement (返回语句中)
6) explicit cast or static cast argument (显示类型转换或者强转)
7) non-type template argument (非类型的模板参数)

In each context, the name of an overloaded function may be preceded by address-of operator & and may be enclosed in a redundant set of parentheses.

In all these contexts, the function selected from the overload set is the function whose type matches the pointer to function, reference to function, or pointer to member function type that is expected by target: the object or reference being initialized, the left-hand side of the assignment, function or operator parameter, the return type of a function, the target type of a cast, or the type of the template parameter, respectively.

The parameter types and the return type of the function must match the target exactly, no implicit conversions are considered (e.g. a function returning a pointer to derived won't get selected when initializing a pointer to function returning a pointer to base).

If the function name names a function template, then, first, template argument deduction is done, and if it succeeds, it produces a single template specialization which is added to the set of overloads to consider. All functions whose associated constraints are not satisfied are dropped from the set. (since C++20) If more than one function from the set matches the target, and at least one function is non-template, the template specializations are eliminated from consideration. For any pair of non-template functions where one is more constrained than another, the less constrained function is dropped from the set (since C++20). If all remaining candidates are template specializations, less specialized ones are removed if more specialized are available. If more than one candidate remains after the removals, the program is ill-formed.

 

你可能感兴趣的:(c++)