Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic template pointer in template class

I have a template class which has a pointer to the same class (but not necessarily using the same type). Here is an example:

template<class T>
class Foo{
    Foo(){}
    Foo* a;
    template<class U>
    void bar(Foo<U>* b){a=b;}
}

When I use it in my main function, everything seems to be working until I use a different template for the argument.

int main(){
    Foo<double> f1;
    Foo<double> f2;
    f1.bar(&f1);// no Errors

    Foo<bool> f3;
    Foo<double> f4;
    f3.bar(&f4);//Error : cannot convert 'Foo<double>*' to 'Foo<bool>*'
}

Is there anyway I can define a pointer in class Foo that has a "generic" pointer to the same class in it?

like image 834
bamia Avatar asked Mar 06 '26 08:03

bamia


1 Answers

Is there anyway I can define a pointer in class Foo that has a "generic" pointer to the same class in it?

What you have is correct. What you are expecting to see is founded on probably a misunderstanding.

Foo<bool> and Foo<double> are totally different classes. Type/class templates allow you to use the compiler to generate new types but they themselves are not classes.

If you had to generate the classes manually, you would have:

class Foo_bool{
    Foo_bool(){}
    Foo_bool* a;

    ...
};

class Foo_double{
    Foo_double(){}
    Foo_double* a;

    ...
};

With that, it's easy to see why you can't use:

Foo_bool a;
Foo_double b;
a.a = &b;   // Not allowed

That is no different than using:

Foo<bool> a;
Foo<double> b;
a.a = &b;   // Not allowed

The closest you can come to achieving your goal is:

  1. Create a base class for all instantiations of Foo.
  2. Store a pointer to the base class.

Simple program that demonstrates the concept:

class FooBase
{
   public:
      virtual ~FooBase() {}
};

template<class T>
class Foo : public FooBase {
   public:
    Foo(){}
    template<class U>
    void bar(Foo<U>* b){a=b;}

   private:
    FooBase* a; // Note the change. This is not Foo* any longer.
};

int main()
{
   Foo<bool> a;
   Foo<double> b;
   a.bar(&b);
}
like image 190
R Sahu Avatar answered Mar 09 '26 00:03

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!