void f(int){}
typedef void (*f_ptr)(int);
struct Functor{
void operator()(int){}
};
struct X{
operator f_ptr(){ return f; }
};
struct Y{
operator Functor(){ return Functor(); }
};
int main(){
X x; Y y;
x(5); // works ?!
y(5); // doesn't ?!
}
Run Code Online (Sandbox Code Playgroud)
Ideone上的实例.输出:
错误:调用'(Y)(int)'不匹配
Q1:为什么调用x(5)允许,即使X只定义了转换为函数指针,而不是operator()?
Q2:相反,如果我们定义转换为另一个仿函数,为什么不允许相同的事情?
我需要一个类型特征,它将根据仿函数的operator()类型和传递给它的参数类型报告仿函数参数的类型.基本上,我需要准确确定将参数传递给仿函数时转换为什么类型.为简单起见,我们假设我只对operator()一个参数感兴趣(可能模板化,可能过载).不幸的是,我只限于c ++ 03.可以吗?如果没有,那么c ++ 11怎么样?
这是一个例子:
#include <cassert>
#include <type_traits>
template<typename Functor, typename Argument>
struct parameter_type
{
// what goes here?
typedef ... type;
};
struct takes_float_cref
{
void operator()(const float &);
};
int main()
{
// when calling takes_float_cref::operator() with an int,
// i'd expect a conversion to const float &
assert(std::is_same(parameter_type<takes_float_cref, int>::type, const float &>::value);
return 0;
}
Run Code Online (Sandbox Code Playgroud)