Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you call a member of member of template parameter?

I seem to be doing something wrong, but I'm not sure what. Here's the smallest example of what I'm trying to do:

#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>();
}

When I try to build this, I get a link error:

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

What am I doing wrong?

like image 918
allyourcode Avatar asked Jan 02 '13 08:01

allyourcode


2 Answers

You need to provide definition for static member call_me:

CallMe TemplateValue::call_me;
int main(int argc, char *argv[]) {
  CallMemberMember<TemplateValue>();
}
like image 79
billz Avatar answered Sep 21 '22 20:09

billz


This has nothing to do with templates: You need to provide the definition for the static class member:

class TemplateValue {
 public:
  static CallMe call_me;
};

CallMe TemplateValue::call_me;

(You should learn to distinguish compiler errors from linker errors. Your code was compiling fine, it was just not complete.)

like image 31
Kerrek SB Avatar answered Sep 24 '22 20:09

Kerrek SB