zell
zell

Reputation: 10204

Superclass for template <int v> class Foo

Suppose that I have a template class

template <int v>
class Foo {...}

I have a function

void f(...)

that accept as inputs any object of Foo<1>, Foo<2> etc, how can I define the function? It seems that

void f(Foo x) 

does not compile. What is a common type for Foo<1>, Foo<100>, ... and all Foo?

Upvotes: 1

Views: 129

Answers (3)

tfkhim
tfkhim

Reputation: 31

As other already pointed out you can use your existing definition of Foo and use a template function foo.

If you really want a common type for all instantiations of your Foo template you have to add it as a base class of Foo.

class FooBase {...};

template<int v>
class Foo : public FooBase {...};

Then you can write a foo function which accepts a pointer or reference to the base class. But this makes only sence if you add some virtual function to your base class which you override in the Foo template class:

#include<iostream>

class FooBase {
  public:
    virtual int doubleIt() const = 0;
};

template<int v>
class Foo : public FooBase {
  public:
   int doubleIt() const {return 2*v;}
};

void foo(FooBase* x) {
  int d = x->doubleIt();
  std::cout << "x->double() is " << d << std::endl;
  // do stuff with d
}

int main() {
    Foo<2> a;
    foo(&a);

    Foo<3> b;
    foo(&b);
}

Demo Code

Upvotes: 1

Daniel
Daniel

Reputation: 8441

You just need to make f a template too:

template <int v>
void foo(Foo<v> x)
{
    // code
}

Upvotes: 1

NathanOliver
NathanOliver

Reputation: 180500

What is a common type for Foo<1>, Foo<100>, ... and all Foo?

There is no common type. What you can do though is make f a template as well

template <int v>
void f(Foo<v> x)
{
    //code here
} 

like above and now the function will accept any Foo you give it.

Upvotes: 5

Related Questions