C++模板与成员函数指针的使用方法

3
下面的代码无法编译,我无法修复它。希望有好心人能够让我理解如何修复这个示例。感谢。
我尝试进行编译:
# 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-主文件

#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

Makefile可以方便地编译代码。
2个回答

4

很遗憾,无法将模板类的实现写入cpp文件中(即使有一种解决方法,如果您确切地知道要使用哪些类型)。 模板类和函数应在头文件中声明和实现。

您必须将Test的实现移动到其头文件中。


不是真的...请参考你链接中的Benoît的回答。 - Jim Balter
@JimBalter,我正要编辑我的答案来插入那个选项。 - Shoe

1
简单的修复方法: 将Test.cpp中函数的定义内联到Test.h类中。
模板类成员函数的定义必须在同一个编译单元中。通常在定义类的同一.h文件中。如果您没有将函数定义内联到类中,而只想在那里添加声明,则需要在每个函数的定义(以及定义的一部分)之前添加“魔法”词template<typename T>。这只是一个大致的答案,为您提供修改参考文档和一些示例的方向。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接