hl037_
hl037_

Reputation: 3887

How to cast template class parameter to const parameter

is there a way to cast a template parameter type ?

say :

#include <list>

class A
{
   int c;
   public:
      A(int a): c(a) {}
};

std::list<const A*> gen()
{
   std::list<A*> list1;
   list1.push_back(new A(5));
   list1.push_back(new A(6));
   return (std::list<const A*>) list1; //Error. Is there a way to cast ?
}

int main()
{

   return 0;
}

A reinterpret_cast seems to work with gcc... but the way reiterpret_cast works is compiler-defined... ( ⇒ platform dependent) (I don't want have to reconstruct another list)

I have to do that because I have a container in a class of object have to modiafiable in the class not outside, but they must still be accessible outside.

Then, what should have been used if say B inherits A, then cast std::list to std::list ?

Upvotes: 0

Views: 342

Answers (1)

juanchopanza
juanchopanza

Reputation: 227418

std::list<A*> and std::list<const A*> are different types and you cannot cast between them. There are a few options, two of which are:

Use the right type from the beginning:

std::list<const A*> list1;
list1.push_back(new A(5));
list1.push_back(new A(6));
return list1;

Return an object of the right type, constructed from the original list1:

std::list<A*> list1;
list1.push_back(new A(5));
list1.push_back(new A(6));
return std::list<const A*>(list1.begin(), list1.end());

Upvotes: 6

Related Questions