vicalomen
vicalomen

Reputation: 11

Call to a templated member function that takes as arguments an object and one of its member function in C++

I am having problems using this declaration.

object1.function1<Object2, void (Object2::*)()>(object2, &Object2::function2)

This is what the compiler tells me.

error LNK2001: unresolved external symbol "public: void __cdecl Object1::function1<class Object2,void (__cdecl Object2::*)(void)>(class Object2 &,void (__cdecl Object2::*)(void))" (??$function1@VObject2@@P81@EAA_NXZ@Object1@@QEAA_NAEAVObject2@@P81@EAA_NXZ@Z)

Here the struct of the code:

class Object1{
public:
    template <typename O, typename F>
    void function1(O& object, F function){
        object.function();
    }
};

class Object2{
public:
    void function2(){
        std::cout << "Doing something..." << std::endl;
    };
};

class Object3 {
private:

    Object1 object1;
    Object2 object2;

    void function3() {
        object1.function1<Object2, void (Object2::*)()>(object2, &Object2::function2);
    };
};

I can not see the error. Someone could help me?

Upvotes: 0

Views: 135

Answers (1)

Jarod42
Jarod42

Reputation: 217810

In

class Object1{
public:
    template <typename O, typename F>
    void function1(O& object, F function){
        object.function();
    }
};

object.function(); doesn't use F function.

Syntax for member function pointer would be:

(object.*function)();

std::invoke is superior, as it allows more than just member function

std::invoke(function, object);

Demo

Upvotes: 1

Related Questions