相关疑难解决方法(0)

如何指定指向重载函数的指针?

我想将重载函数传递给std::for_each()算法.例如,

class A {
    void f(char c);
    void f(int i);

    void scan(const std::string& s) {
        std::for_each(s.begin(), s.end(), f);
    }
};
Run Code Online (Sandbox Code Playgroud)

我期望编译器f()通过迭代器类型来解析.显然,它(GCC 4.1.2)没有这样做.那么,我该如何指定f()我想要的?

c++ stl

128
推荐指数
6
解决办法
3万
查看次数

如何获取重载成员函数的地址?

我正在尝试获取指向特定版本的重载成员函数的指针.这是一个例子:

class C
{
  bool f(int) { ... }
  bool f(double) { ... }

  bool example()
  {
    // I want to get the "double" version.
    typedef bool (C::*MemberFunctionType)(double);
    MemberFunctionType pointer = &C::f;   // <- Visual C++ complains
  }
};
Run Code Online (Sandbox Code Playgroud)

错误消息是"错误C2440:'初始化':无法从'重载函数'转换为'MemberFunctionType'"

如果f没有重载,这可以工作,但不是在上面的例子中.有什么建议吗?

编辑

请注意,上面的代码并没有反映我的现实世界问题,那就是我忘记了一个"const" - 这就是被接受的答案所指出的.不过,我会留下问题,因为我觉得问题可能发生在其他人身上.

c++ overloading pointer-to-member

18
推荐指数
1
解决办法
1万
查看次数

C++重载函数指针歧义

我正在尝试传递一个重载的函数指针,如下面的示例代码所示.

class Sample
{
  uint32_t method(char* input1, double input2);
  uint32_t method(double input1);
}

template<class T, class... Args)
void processInput(T &&t, Args&&... a)
{
  std::packaged_task<uint32_t(Args...)> task(std::bind(t, a...));
  // other processing
}

// Caller invokes the below API
Sample* obj = new Sample();
processInput(static_cast<uint32_t(*)(double)>(&Sample::method), &*obj, 2.0f);
Run Code Online (Sandbox Code Playgroud)

但是这段代码没有编译.它一直在抱怨它无法确定哪个重载函数实例.我举了几个例子:

C++重载方法指针

http://en.cppreference.com/w/cpp/language/static_cast

有人可以帮忙指出这里出了什么问题吗?

c++ function-pointers static-cast

3
推荐指数
1
解决办法
1317
查看次数