Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;使用成员函数指针的模板用法_C++_Templates_Member Function Pointers - Fatal编程技术网

C++ c++;使用成员函数指针的模板用法

C++ c++;使用成员函数指针的模板用法,c++,templates,member-function-pointers,C++,Templates,Member Function Pointers,下面的代码根本无法编译,我无法修复它。 希望一个好的灵魂能让我明白如何修复这个例子 谢谢你 我尝试编译: # 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: e

下面的代码根本无法编译,我无法修复它。 希望一个好的灵魂能让我明白如何修复这个例子

谢谢你

我尝试编译:

# 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
其他.cpp

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


Other::Other() {
}

void Other::printOther() {
        printf("Other!!\n");
}
Makefile将允许轻松编译。

不幸的是,将模板类的实现写入cpp文件(即使您确切知道要使用的类型)。模板类和函数应该在头文件中声明和实现

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

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


模板类的成员函数的定义必须在同一编译器单元中。通常在定义类的同一个.h中。如果没有将函数的定义内联到类中,并且只需要声明,则需要在每个函数的定义(以及定义的一部分)之前添加“神奇”单词
模板
。这只是一个大致的答案,为您提供了修改参考文件的方向和一些示例。

不正确。。。请在您的链接上查看贝诺特的答案。@JimBalter,我正要编辑我的答案以插入该选项。
#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
#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)();
}
#ifndef OTHER_H
#define OTHER_H

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

#endif
#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