5

我似乎做错了什么,但我不确定是什么。这是我正在尝试做的最小示例:

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

我究竟做错了什么?

4

3 回答 3

8

您需要为静态成员提供定义call_me

CallMe TemplateValue::call_me;
int main(int argc, char *argv[]) {
  CallMemberMember<TemplateValue>();
}
于 2013-01-02T08:39:41.360 回答
3

这与模板无关:您需要为静态类成员提供定义:

class TemplateValue {
 public:
  static CallMe call_me;
};

CallMe TemplateValue::call_me;

(你应该学会区分编译器错误和链接器错误。你的代码编译得很好,只是不完整。)

于 2013-01-02T08:40:51.633 回答
0

您声明call_me为静态的。静态对象需要定义,就像方法和函数一样。您需要像这样初始化它:

CallMe TemplateValue::call_me = CallMe();
于 2013-01-02T08:42:20.620 回答