Search code examples
c++function-pointers

term does not evaluate to a function taking 1 arguments


Can someone explain why I am getting:

error C2064: term does not evaluate to a function taking 1 arguments

for the line:

DoSomething->*pt2Func("test");

with this class

#ifndef DoSomething_H
#define DoSomething_H

#include <string>

class DoSomething
{
public:
    DoSomething(const std::string &path);
    virtual ~DoSomething();

    void DoSomething::bar(const std::string &bar) { bar_ = bar; }

private:
    std::string bar_;
};

#endif DoSomething_H

and

#include "DoSomething.hpp"

namespace
{

void foo(void (DoSomething::*pt2Func)(const std::string&), doSomething *DoSomething)
{
    doSomething->*pt2Func("test");
}

}

DoSomething::DoSomething(const std::string &path)
{
    foo(&DoSomething::bar, this);

}

Solution

  • Problem #1: The name of the second argument and the type of the second argument are swapped somehow. It should be:

          DoSomething* doSomething
    //    ^^^^^^^^^^^  ^^^^^^^^^^^
    //    Type name    Argument name
    

    Instead of:

        doSomething* DoSomething
    

    Which is what you have.

    Problem #2: You need to add a couple of parentheses to get the function correctly dereferenced:

        (doSomething->*pt2Func)("test");
    //  ^^^^^^^^^^^^^^^^^^^^^^^
    

    Eventually, this is what you get:

    void foo(
        void (DoSomething::*pt2Func)(const std::string&), 
        DoSomething* doSomething
        )
    {
        (doSomething->*pt2Func)("test");
    }