use*_*989 4 c++ templates friend
如何get在可以访问私有构造函数的封闭范围中创建函数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);
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试通过制作inner一个template <typename V, typename W> friend inner<V> get(outer<W>&);但却无法正常工作来宣布它.
我已经尝试通过制作
inner模板来宣布它<typename V, typename W> friend inner<V> get(outer<W>&);
你需要在friend声明之前声明模板函数,告诉编译器这get是一个函数模板.例如
// 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 {};
}
Run Code Online (Sandbox Code Playgroud)