0

This code is not able to resolve void K::func<B>(B&).

struct K {
  template <typename T> void func(T &t);
};

struct B {
  void ok();
};

// definition
template <typename T> void K::func(T &t) { t->ok(); }

// getting: undefined reference to `void K::func<B>(B&)'
// nm says '                 U void K::func<B>(B&)'
template <> void K::func<B>(B &b);
template <> void K::func(B &b);

int main() {
  K k;
  B b;
  k.func(b);
};

Note: Several other questions at SO were related to compilation; I m stuck at linking . Please point me to duplicate if any.

UPDATE: I'm following http://en.cppreference.com/w/cpp/language/template_specialization , look for functions g1 or g2 ;

UPDATE2: fixed 'func' to 'K::func' to fix 'out of class member template definition', still K::func can't be specialized.

vrdhn
  • 4,024
  • 3
  • 31
  • 39

2 Answers2

3

You need to provide definition like this:

template <> void K::func<B>(B &b) {}

Also the following two are equivalent only in the second case T is deduced from the parameter type:

template <> void K::func<B>(B &b);
template <> void K::func(B &b);
Yola
  • 18,496
  • 11
  • 65
  • 106
  • I've `template void func(T &t) { t->ok(); }` .. the question is how to specialize it for T = B ! , not to redefine func for T = B – vrdhn Mar 18 '18 at 07:56
  • @vrdhn but this template is not related to `struct K`. For struct K you can write `template<> void K::func(B &b) { b.ok(); }`. – Yola Mar 18 '18 at 07:59
  • oh yeah .. Thanks, i guess I needed another paid eyes (-: But stil, this defination needs to be templatized for my use case. – vrdhn Mar 18 '18 at 08:05
  • But for several class B,C,D..., I'll need to reimplment it. – vrdhn Mar 18 '18 at 08:13
0

It turns out that template <> void K::func(B &b); is only a declaration, for definition template void K::func(B &b); is needed. The updated code:

struct K {
  template <typename T> void func(T &t);
};

struct B {
  void ok();
};

// definition
template <typename T> void K::func(T &t) { t.ok(); }
// specialiation: Do NOT put template <> here !!!    
template void K::func(B &b);

int main() {
  K k;
  B b;
  k.func(b);
};
vrdhn
  • 4,024
  • 3
  • 31
  • 39