0

I have a problem to cast a child class when that's from function who receive a parent class. I think it's a similar problem like here C++ cast to derived class. I try to implement a solution with this post but I don't find any succes.

error message

vec_template clang++  -std=c++11 -Wconversion *.cpp && ./a.out
main.cpp:8:18: error: dynamic_cast from rvalue to reference type 'vec2<float> &'
        vec2<T> &temp = dynamic_cast<vec2<T>&>(&v);
                        ^~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:33:2: note: in instantiation of function template specialization 'show_data<float>'
      requested here
        show_data(a);
        ^
main.cpp:8:18: error: 'vec<float> *' is not a class
        vec2<T> &temp = dynamic_cast<vec2<T>&>(&v);
                        ^                      ~~
2 errors generated.

code

#include "vec2.cpp"
#include <iostream>
#include <cstdio>

template <class T>
void show_data(vec<T> &v) {
    vec2<T> &temp = dynamic_cast<vec2<T>&>(&v);
    std::cout << "v.x(): " << temp.x() << std::endl;
    std::cout << "v.y(): " << temp.y() << std::endl;
}


int main() {
    vec2<float> a;

    std::cout << a << std::endl;

    show_data(a);
    a.x(2);
    show_data(a);

    printf("instance vec2 float: %i\n", vec2<float>::get_instance());

    return (0);
}

where vec2 is

template <class T>
class vec2 : public vec<T> {
  //
};
Knupel
  • 323
  • 2
  • 14
  • 2
    It's quite well explained that you are trying to cast `'vec *' is not a class` `to reference type 'vec2 &'`. & is odd here: `&v`. – 273K Apr 06 '20 at 19:32
  • 2
    You are casting from a pointer to a reference. Those are incompatible types. Also, `#include "vec2.cpp"` is rather troubling. – Drew Dormann Apr 06 '20 at 19:44
  • I found the solution, it's between both comment. first I pass a reference and after a Iread the reference od reference...it's little to much. After that I'de a polymorphic problem, because I need to add a virtual destructor to the parent class. Et voilà. Thanks for the comment that's help me. https://stackoverflow.com/users/6752050/s-m && https://stackoverflow.com/users/16287/drew-dormann – Knupel Apr 07 '20 at 17:37

0 Answers0