Thomas B.
Thomas B.

Reputation: 721

Enum in template Struct

My problem is the same as this guy had: Link

It was not possible then and is not possible now, but my actual question is this:

Wasn't there something in the works for the upcoming C++ Standards (17 and later) that allowed it? I'm almost 100% certain that I read something along these lines somewhere.

I would imagine that it was some sort of wrapper that simply returned an object of the template initialized with void and then allowed the enum access this way.

Can someone point me in the right direction?

Thanks!

Upvotes: 0

Views: 762

Answers (2)

Aziuth
Aziuth

Reputation: 3902

Please consider this code:

#include <iostream>

template<typename T>
class SomeClass;

template<>
class SomeClass<int>
{
public:
    enum SomeEnum { A=1, B=2 };
};

template<>
class SomeClass<double>
{
public:
    enum SomeEnum { A=4, B=5 };
};


int main()
{
  std::cout << SomeClass<int>::SomeEnum::A << std::endl;
  std::cout << SomeClass<double>::SomeEnum::A << std::endl;
}

(I tested it on http://cpp.sh/7xc3 )

The output is 1 and 4. Alternatively, I could give one of those the enum values C and D, or maybe B and C.

Therefore, there is no unambiguous possibility of what SomeClass::SomeEnum::A is supposed to be. Now, those are the integer values, but also consider that SomeClass<int>::SomeEnum::A != SomeClass<double>::SomeEnum::A.

This is an explanation of why what you ask for couldn't possibly work. I think you have in mind that one writes a template class in one single implementation, and in such a case, it wouldn't be ambiguous. But that is just the common way to do it, not the technical meaning. After all, SomeClass<int> is a different class to SomeClass<double> altogether. They are to the machine two completely separate classes like SomeClassInt and SomeClassDouble, and as I shown above, they can have totally different implementations.

Also, even if you state one implementation in general, a different person could still write a specialized implementation later on that would totally work with your code without rewriting it. So a single implementation existing would not mean that it will stay unambiguous in the future. That would be a major problem.

That said, the answer of the question in your link provides a good way to solve the issue using a common base class. Is there a reason you don't use that one?

In any case, reflect about the meaning of the enum here in the organical thought process of OOP. Do you have an example where you need it? Let's talk about that one, might be a XY-problem.

Upvotes: 2

Matthieu Brucher
Matthieu Brucher

Reputation: 22043

They are different types, I don't think this will change like ever.

Think of what happens if there is a template specialization that changes the enum values but not their "names".

Upvotes: 4

Related Questions