2

I wanted to create a template class that would provide generic means for a class to have a member m_Type that designates some kind of type provided by the inheriting class. Consider this:

template<typename T>
struct TypeAttribute
{
    T m_Type;
};

template<typename T>
struct TypeAttribute2
{
    using Type = typename T::Type;
    Type  m_Type;
};

struct Foo : TypeAttribute<Foo::Type>
{
    enum class Type
    {
        Type1
    };
};

struct Bar : TypeAttribute2<Bar>
{
    enum class Type
    {
        Type1
    };
};

Both of these fail due to incomplete types (in the first case Foo::Type and in the second Bar::Type) which is understandable. Am I missing something trivial or is this just a wrong approach and I should move the nested types outside the classes (I simply wanted the classes to contain the relevant types inside themselves not to populate higher namespaces). Live demo here.

Rudolfs Bundulis
  • 11,636
  • 6
  • 33
  • 71

1 Answers1

2

At the time you declare struct Foo and inheriting from TypeAttribute, Foo is not a complete type yet. Same for struct Bar.
Your problem is very close to this post.

Perhaps this code I made can help you Live Demo

#include <iostream>
#include <string>
#include <memory>

enum class ChildType
{
    Child1,
    Child2
};

template <typename Derived>
struct Parent
{
    void DisplayChildType() const
    {
        switch (Derived::type_)
        {
            case ChildType::Child1: std::cout << "Child1" << std::endl; break;
            case ChildType::Child2: std::cout << "Child2" << std::endl; break;
            default:;
        }
    }
};

struct Child1 : Parent<Child1>
{
    static constexpr ChildType type_ = ChildType::Child1;
};

struct Child2 : Parent<Child2>
{
    static constexpr ChildType type_ = ChildType::Child2;
};

template <typename Type>
void DisplayType(const Type& child)
{
    const Parent<Type>* asParent = &child;
    asParent->DisplayChildType();
}

int main()
{
    Child1 child1;
    Child2 child2;

    DisplayType(child1);
    DisplayType(child2);
}
Community
  • 1
  • 1
Richard Dally
  • 1,432
  • 2
  • 21
  • 38
  • Well as I stated I was aware that the types are incomplete - I hoped that that maybe some kind of c++11 magic will overcome this. So I'll just have to put the enumerations in a higher scope. – Rudolfs Bundulis Aug 07 '15 at 15:53