0

Assume that class C contains a function doSomething that is called repeatedly and its results are mandatory for a bunch of other functions of different classes. So in this case the function start of class B. This should operate from another class C. I think that should be pretty easy with std::bind.

But this only works if doSomething belongs to C. If I'm calling it from another class I'm getting a linker error. What am I missing?

#include <iostream>
#include <functional>
class A {
public:
    A() {}
    template<typename Callable>
    void doSomething(Callable f); 
};

template<typename Callable>
void A::doSomething(Callable f) {
    // do some stuff 
    int input = 1;
    f(input); // B::start should be called here
}

class B {
    public:
         B() {}
         void start(int input);
};

void B::start(int input) {
    std::cout << "dostuff" << std::endl;
    // do some other stuff
}

class C {
    private:
        A a;
    public:
        C() : a() {
            B b;
            a.doSomething(std::bind(&B::start, b, std::placeholders::_1)); 
            // if doSomething would be a member of class C then 
            // doSomething(std::bind(&B::start, b, std::placeholder//::_1) would work 
        }
};

int main() {
   C c;
}

What am I missing?

Undefined symbols for architecture x86_64:
  "void A::doSomething<std::_Bind<void (B::*(B))()> >(std::_Bind<void (B::*(B))()>)", referenced from:
      C::C(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) in C.cpp.o
      C::C(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) in C.cpp.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
Borderline
  • 53
  • 4
  • 1
    What error are you getting? – NathanOliver Mar 25 '20 at 13:39
  • `er::_1) ` -> `er::_1) );` – KamilCuk Mar 25 '20 at 14:20
  • Does this answer your question? [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – KamilCuk Mar 25 '20 at 14:22
  • @NathanOliver I updated the question with the error message. – Borderline Mar 25 '20 at 14:22
  • Looks like this is a dupe of: https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – NathanOliver Mar 25 '20 at 14:22
  • 1
    Is the code you've shown for class `A` the real code? Or have you actually put the definition of `A::doSomething` in a .cpp file? – G.M. Mar 25 '20 at 14:23
  • @G.M. I updated the code how I use it in my code.. oddly enough it works on an online compiler. I guess I have to double-check it once again. – Borderline Mar 25 '20 at 14:56

0 Answers0