0

"A.h"

template<class T>
struct A 
{
    void foo();
};

template<class T>
struct B : A<T> {};

"A.cpp"

template<class T>
void A<T>::foo()
{
}

template struct B<int>;

When I call method foo of B in other source files it doesn't build because of unresolved external symbol. Why isn't A defined with B? I find that weird at least. Is there a way to force A definition from definitions of B? I tried adding "using A::foo;" to struct B but it didn't change anything.

I know I can simply define A but I don't want to because in my real code "A" contains more template parameters than "B" and I am worried than I will make mistake that will not be detected until someone writes code that requires those unresolved methods. Also I am very curios as to why it doesn't work.

sluki
  • 524
  • 5
  • 15
  • 1
    How is this question duplicate of that question? Because someone somewhere in the answers mentions it? – sluki May 26 '15 at 15:42
  • `A` needs to be explicitly instantiated because `A::foo` is bound by `A`, even if it is inherited. Unless you hid `A::foo` and provided your own `foo` in `B`. – David G May 26 '15 at 15:57

1 Answers1

0

Define A::foo in the .h file.

A.h

template<class T>
struct A 
{
    void foo();
};

template<class T>
struct B : A<T> {};

template<class T>
void A<T>::foo()
{
}

A.cpp

template struct B<int>;
Aumnayan
  • 671
  • 3
  • 12