0

I want to make a template class on my main.cpp then process it on another class which is from another header/cpp

Heres my code:

Main.cpp

#include <iostream>
#include "test.h"


template<typename B>
class foo{

};


int main() {

return 0;
}

test.h

namespace sn{
class A{
    public:
        void getint(foo<int> asd);    //error because it doesn't know foo
};
}

test.cpp

#include<iostream>
#include "test.h"

namespace sn{

void A::getint(foo<int> asd){   //error because it doesn't know foo

}    
}   

So how can i pass an instance of a template class from or introduce "foo" from main.cpp? do i have to change my design?

Carlos Miguel Colanta
  • 2,685
  • 3
  • 31
  • 49

1 Answers1

0

The obvious method would be to move the definition of foo into a header as well:

foo.h:

template<typename B>
class foo{

};

test.h:

#include "foo.h"

namespace sn {
struct A {
    void getint(foo<int>);
};
}

From the looks of things, test.cpp would remain unchanged, and main.cpp would just have its definition of foo deleted.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • I see thank you. do i have to make foo.cpp to implement the prototypes from foo.h? – Carlos Miguel Colanta May 22 '15 at 22:51
  • @CarloBrew: at least in most typical cases, you want to put the entire implementation of a template into the header (not ideal, but such is life until modules get added to the language). – Jerry Coffin May 22 '15 at 22:58
  • I see. so my only choice is to implement everything to the header? – Carlos Miguel Colanta May 22 '15 at 23:09
  • @CarloBrew: It's not the only possible choice, but it is the most common one. If (for example) you know *a priori* all the types over which the template will ever be instantiated, you can move the implementations into a source file, and explicitly instantiate the template over each of those types. – Jerry Coffin May 22 '15 at 23:16