Home > Net >  Nested Type of Template not depending on Template Arguments
Nested Type of Template not depending on Template Arguments

Time:09-20

I've been struggeling with the following problem:

// this is in a header file
template <typename T>
struct Foo {
    T x, y;
    // ... other stuff

    struct Bar {
        int a, b;
        // ... other stuff
        void f() const;
    };

    Bar h() const
    { return { reinterpret_cast<int>(this->x), reinterpret_cast<int>(this->y) }; }
};

It's clear that Foo::h() needs to be implemented in the header file since it depends on the template argument. But this is not the case for Foo::Bar::f(). I would like to implement this in a separate .cpp-file, since it only needs to compile once and so on.

Just as a note: I would like to keep this as a nested type for namespacing reasons.

Is there a nice way to do this ? I dont't see why this shouldn't work, since Foo::Bar does not depend on the template argument at all.

Thank you very much !

Edit: fixed typo

CodePudding user response:

I dont't see why this shouldn't work, since Foo::Bar does not depend on the template argument at all

This is not correct conclusion - the nested class has access to all names (private, protected, etc) to which the enclosing class has access, so depending on how the enclosing class is instantiated, the nested class has different surrounding context, thus Foo<int>::Bar and Foo<char>::Bar are not the same classes (to be precise - the nested class is part of the enclosing class definition, so without Foo<int>/Foo<char>, Bar doesn't exist, but since these are different classes, Bar under those classes are also different)

CodePudding user response:

not sure what you mean by "namespacing reasons", but if you just want to access it like Foo<T>::Bar, you can use alias.

struct ChocolateBar {
    int a, b;
    // ... other stuff
    void f() const;
};

template <typename T>
struct Foo {
    T x, y;
    // ... 
    using Bar = ::ChocolateBar;
    Bar h() const { return { reinterpret_cast<int>(this->x), reinterpret_cast<int>(this->y) }; }
};
  • Related