简体   繁体   中英

Why Doesn't This Using Declaration on a `template` Class's Enum Work?

This compiles:

template <typename T> class Parent { public:
  enum MyEnum { RED,GREEN,BLUE };
};
class Child : public Parent<int> { public:
  using Parent<int>::MyEnum;
  int foo() { return GREEN; }
};
void tester() { Child d; d.foo(); }

This doesn't (on gcc, this outputs error: 'GREEN' was not declared in this scope ):

template <typename T> class Parent { public:
  enum MyEnum { RED,GREEN,BLUE };
};
template <typename T> class Child : public Parent<T> { public:
  using Parent<T>::MyEnum;
  int foo() { return GREEN; }
};
void tester() { Child<int> d; d.foo(); }

My question: why? (Also, any suggestions for a workaround?)

For the second code :

  1. You need to add the typename keyword because you access the type MyEnum is dependent on T. Change the line of the using to this :

using typename Parent<T>::MyEnum;

  1. Then, in the method foo you need to specify that GREEN is a member of the enum MyEnum like that :

int foo() { return MyEnum::GREEN; }

compiled fine for me with gcc and clang with C++11
Live example here

It worked in the first example because MyEnum in the line of the using is not dependent of a template type T. You used explicitly Parent with type int.

The line

using Parent<int>::MyEnum;

has no bearing on being able to use GREEN in the line

int foo() { return GREEN; }

You can remove the first line and the second line should continue to work.

As for the second example, you can use:

template <typename T> class Child : public Parent<T>
{
    public:
      using Parent<T>::GREEN;
      int foo() { return GREEN; }
};

It's not immediately clear to me why Parent<T>::GREEN is not automatically available in Child

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