user2050516
user2050516

Reputation: 760

c++ template usage with member function pointer

The below simply does not compile and I cannot fix it. Hope a good soul can make me understand how to fix this example.

thanks in

I try to compile:

# make
g++    -c -o client.o client.cpp
client.cpp: In function `int main()':
client.cpp:7: error: missing template arguments before "t"
client.cpp:7: error: expected `;' before "t"
client.cpp:8: error: `t' undeclared (first use this function)
client.cpp:8: error: (Each undeclared identifier is reported only once for each function it appears in.)
<builtin>: recipe for target `client.o' failed
make: *** [client.o] Error 1

client.cpp - the main

#include<stdio.h>
#include"Test.h"
#include"Other.h"

int main() {

        Test<Other> t = Test<Other>(&Other::printOther);
        t.execute();

        return 0;
}

Test.h

#ifndef TEST_H
#define TEST_H

#include"Other.h"

template<typename T> class Test {

        public:
                Test();
                Test(void(T::*memfunc)());
                void execute();

        private:
                void(T::*memfunc)(void*);
};

#endif

Test.cpp

#include<stdio.h>
#include"Test.h"
#include"Other.h"


Test::Test() {
}

Test::Test(void(T::*memfunc)()) {
        this->memfunc= memfunc;
}

void Test::execute() {
        Other other;
        (other.*memfunc)();
}

Other.h

#ifndef OTHER_H
#define OTHER_H

class Other {
        public:
                Other();
                void printOther();
};

#endif

Other.cpp

#include<stdio.h>
#include"Other.h"


Other::Other() {
}

void Other::printOther() {
        printf("Other!!\n");
}

Makefile

all: main

main: client.o Test.o Other.o
        g++ -o main $^

clean:
        rm *.o

run:
        ./main.exe

The Makefile will allow easy compiling.

Upvotes: 3

Views: 946

Answers (2)

qPCR4vir
qPCR4vir

Reputation: 3571

Simple fix: move the definition of the function in Test.cpp inline into the class in Test.h

The definition of the member function of the template class have to be in the same compiler-unit. Usually in the same .h where the class is defined. If you don’t made inline into the class the function’s definition, and want there only the declaration, you will need to add before the definition (well as part of the definition) of each function the "magic" words template<typename T>. This is only an approximately answer to give you the direction to revise the reference doc, and some examples.

Upvotes: 1

Shoe
Shoe

Reputation: 76240

Unfortunately it's not possible to write the implementation of a template class into a cpp file (even though there is a workaround if you know exactly what types you are going to use). Template class and functions should be declared and implemented inside the header file.

You have to move the implementation of Test inside its header file.

Upvotes: 4

Related Questions