相关疑难解决方法(0)

为什么'X x; X();' 允许,当'X'定义转换为函数指针时,但不是,当它定义转换为仿函数时?

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:相反,如果我们定义转换为另一个仿函数,为什么不允许相同的事情?

c++ function-pointers functor function-call

29
推荐指数
1
解决办法
1067
查看次数

给定传递给它的参数类型,如何确定函数参数的类型?

我需要一个类型特征,它将根据仿函数的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)

一个相关的问题(答案并不能满足我的需要)给出了需要这样一个特征的背景.我已经对ideone进行了进一步的单元测试.

c++ templates parameter-passing c++11

13
推荐指数
1
解决办法
495
查看次数