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;
}

测试.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

测试.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)();
}

其他.h

#ifndef OTHER_H
#define OTHER_H

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

#endif

其他.cpp

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


Other::Other() {
}

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

生成文件

all: main

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

clean:
        rm *.o

run:
        ./main.exe

Makefile 将允许轻松编译。

4

2 回答 2

4

不幸的是,不可能将模板类的实现写入 cpp 文件(即使如果您确切知道要使用的类型有一种解决方法)。模板类和函数应该在头文件中声明和实现。

您必须Test在其头文件中移动实现。

于 2013-03-27T09:50:52.760 回答
1

简单修复:将 Test.cpp 中的函数定义内联移动到 Test.h 中的类中

模板类的成员函数的定义必须在同一个 compiler-unit中。通常在定义类的同一个 .h 中。如果您没有将函数的定义内联到类中,并且只想要声明,则需要在每个函数的定义(以及定义的一部分)之前添加“魔术”字样template<typename T>。这只是为您提供修改参考文档的方向和一些示例的大致答案。

于 2013-03-27T09:51:07.343 回答