简体   繁体   中英

How to use using with CRTP?

When creating types with no additional features, I try to use using , rather than subclassing or using typedef .

I have a CRTP hierarchy where I am trying to propagate the concrete type up the tree.

GrandKid seems to compile fine. Is there a way to get GrandKid_2 to work?

ERROR MESSAGE

junk.cpp:18:26: error: ‘GrandKid_2’ was not declared in this scope

CODE

template<typename T>
struct Parent
{
};

template<typename T>
struct Child
    : public Parent<T>
{
};

struct GrandKid : 
    public Child<GrandKid>
{
};

// using GrandKid_2 = Child<GrandKid_2>;   // doesn't compile

int
main( int argv, char* argc[] )
{
    GrandKid gk;  // ok
}

using , like typedef , creates an alias, not a new type. Therefore, you cannot use GrandKid_2 to define itself.

You will surely need to create a new type :

struct GrandKid_2 : Child<GrandKid_2> {};

By the way, do you really want GrandKid_2 to be its own child ? Maybe you meant using GrandKid_2 = Child<GrandKid>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM