Inheritance and templates

Hello,

I've been racking my brains over how I might go about implementing something like this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class CBase {
public :
	CBase() {}
	void foo(); //Method that uses 'bar'.

	vec2</*let sub-classes decide*/> bar;
};

class CNeedsFloat : public CBase {
public :
	CNeedsFloat() {foo();}

	//vec2<float> bar;

};

class CNeedsShort : public CBase {
public :
	CNeedsShort() {foo();}

	//vec2<short> bar;

};


Might not be the best example. Whatever.
Any help would be appreciated.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <vector>
#include <string>
#include <iostream>

template < typename T  > struct base 
{
   void foo( const T& v = T() ) {  seq.push_back(v) ; }
   std::vector<T> seq ;
};

template < typename T > struct derived : base<T> {} ;

int main()
{
   derived<int> a ;
   a.foo(100) ;
   
   derived< void* > b ;
   b.foo( &a ) ;
   
   derived< std::string > c ;
   c.foo( "abcd" ) ;
   
   struct needs_short : base<short>
   {
       needs_short() { foo() ; } 
   };
   
   needs_short ns ;
   std::cout << ns.seq.size() << '\n' ; // 1
}

http://liveworkspace.org/code/1rS1IH$0
Thanks for this! Works as you would expect.
Topic archived. No new replies allowed.