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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With