Search code examples
c++c++11void-pointersauto

C++11 auto and void* generics


Based upon this, can I infer that int age = 45; auto* page = &age; std::cout << *page; will allow true generics in c++ whereas void* requires knowledge of the type to cast it and grab the value?

I am studying c++ again and thought auto* would be a very suitable and ideal replacement for void*.


Solution

  • I am studying c++ again and thought auto* would be a very suitable and ideal replacement for void*.

    No, that won't work.

    int i;
    auto* p1 = &i;
    double d;
    auto* p2 = &d;
    
    p1 = p2; // Won't work.
    

    Even though p1 and p2 are declared using the auto keyword, the types of those objects are different. They are int* and double*, respectively.

    Had we used

    void* p1 = &i;
    void* p2 = &d;
    

    The following would be OK.

    p1 = p2;
    

    Support for generics is not provided at the core language level. You'll have to use std::any or boost::any to get support for generics.