我似乎做错了什么,但我不确定是什么。这是我尝试做的最小的例子:
#include <iostream>
using std::cout;
class CallMe {
public:
void Maybe() {
cout << "A";
}
};
class TemplateValue {
public:
static CallMe call_me;
};
template<typename T>
void CallMemberMember() {
T::call_me.Maybe();
}
int main(int argc, char *argv[]) {
CallMemberMember<TemplateValue>();
}
当我尝试构建它时,我收到链接错误:
$ clang++ --std=c++11 repro_link_error.cc
Undefined symbols for architecture x86_64:
"TemplateValue::call_me", referenced from:
void CallMemberMember<TemplateValue>() in repro_link_error-9BE9gw.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
我做错了什么?
答案 0 :(得分:8)
您需要提供静态成员call_me
的定义:
CallMe TemplateValue::call_me;
int main(int argc, char *argv[]) {
CallMemberMember<TemplateValue>();
}
答案 1 :(得分:3)
这与模板无关:您需要为静态类成员提供定义:
class TemplateValue {
public:
static CallMe call_me;
};
CallMe TemplateValue::call_me;
(你应该学会区分编译器错误和链接器错误。你的代码编译得很好,但是还不完整。)
答案 2 :(得分:0)
您将call_me
声明为静态。静态对象需要像方法和函数一样进行定义。你需要像这样初始化它:
CallMe TemplateValue::call_me = CallMe();