开发者

Casting problem in C++/CLI - won't compile

开发者 https://www.devze.com 2023-03-22 15:12 出处:网络
I have the following in C++/CLI: (take note of my errors in comments) class Base{...} class Derived : public Base{...}

I have the following in C++/CLI: (take note of my errors in comments)

class Base{...}   

class Derived : public Base{...}

public ref class CliClass
{
    public:
    std::list&开发者_运维技巧lt;Base*> *myList;

    CliClass()
    {
    myList = new list<Base*>();
    }

    AddToList(Derived *derived)
    {
        myList->push_back(derived);
    }

    DoCast()
    {
        Derived *d = nullptr;

        int n = (int)myList->size();
        for(int i = 0; i < n; i++)
        {

        //this following does not compile
        //error C2440: 'type cast' : cannot convert from 'std::list<_Ty>' to 'Derived *'

        d = (Derived*)myList[i];    

        //I've also tried this -which does not compile
        //error C2682: cannot use 'dynamic_cast' to convert from 'std::list<_Ty>' to 'Derived *'

        d = dynamic_cast<Derived*>(myList[i]);


        }
    }
}

I would like to cast myList[i] to the Derived type.. but it won't allow me.

Any suggestions on how to cast this properly? (compile and is run-time safe - i.e. won't blow up if wrong type)


You got it all wrong. Assuming that you have several typos in your code and mean std::list, you are currently saying:

std::list<Base*> * myList;

/* ... */

myList[i] = /* ... */ ;

The last line treats myList as an array of lists, which you never created! The way to access list elements is by iteration.

Here is a skeleton rewrite, hopefully you'll be able to extract the fixes from that:

public ref class CliClass
{
public:
  std::list<Base*> * myList;

  CliClass() : myList(new std::list<Base*>()) { }

  DoCast()
  {
    for(auto it = myList->cbegin(), end = myList->cend(); it != end; ++it)
    {
      Derived * const d = dynamic_cast<Derived*>(*it);
      /* do something useful with d */
    }
  }
};


C++ in std::list doesn't have an operator[].
Besides it's std::list and NOT std:List.

So the code is probably trying to convert the list into a Derived* and then will probably try to use the [] operator on the result.

So just find another way to store the data (for example std::map<int,Base*>).

Something like this:

std::for_each(myList.begin(), myList.end(), DoSomething);

void DoSomething(Base* item)
{
   Derived* d = dynamic_cast<Derived*>(item);

}

Or a straight-forward approach (if you don't have the right macros):

for (std::vector<Base*>::iterator item = myList.begin(); item  != myList.end(); ++item ) { //Iterate through 'myList'
   Derived* d = dynamic_cast<Derived*>(*item );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消