Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How can I make get a function in the enclosing scope that can access the private constructor of 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 have tried declaring it out of class by making inner have a template <typename V, typename W> friend inner<V> get(outer<W>&); but that didn't work either.

like image 884
user975989 Avatar asked Nov 05 '17 05:11

user975989


1 Answers

I have tried declaring it out of class by making inner have a template <typename V, typename W> friend inner<V> get(outer<W>&);

You need to declare the template function before the friend declaration, to tell the compiler that get is a template. E.g.

// 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

like image 120
songyuanyao Avatar answered Sep 21 '22 08:09

songyuanyao