How to declare a template function as a friend of a template nested class?

How can I make a getfunction in a scope that can access a private constructor outer<T>::inner<U>?

template <typename T>
struct outer {
    template <typename U>
    class inner {
        inner() {}
    public:
        friend inner get(outer&) {
            return {};
        }
    };
};


int main() {
    outer<int> foo;
    outer<int>::inner<float> bar = get<float>(foo);
}

I tried to declare it outside the class by doing inner template <typename V, typename W> friend inner<V> get(outer<W>&);, but that didn't work either.

+4
source share
1 answer

I tried declaring it outside the class by creating a innertemplate<typename V, typename W> friend inner<V> get(outer<W>&);

You need to declare a template function before declaring a friend to tell the compiler what the getfunction template is. eg.

// definition of outer
template <typename T>
struct outer {

    // forward declaration of inner
    template <typename U>
    class inner;
};

// declaration of get
template <typename V, typename W> 
typename outer<W>::template inner<V> get(outer<W>&);

// definition of inner
template <typename T>
template <typename U>
class outer<T>::inner {
    inner() {}
    public:
    // friend declaration for get<U, T>
    friend inner<U> get<U>(outer<T>&);
};

// definition of get
template <typename V, typename W> 
typename outer<W>::template inner<V> get(outer<W>&) {
    return {};
}

Live

+4
source

Source: https://habr.com/ru/post/1688747/


All Articles