考慮下面的代碼:A <T>的朋友也可以A <A<T>>的朋友嗎?
#include <vector>
template<typename T> class Container;
template<typename T> Container<Container<T>> make_double_container(const std::vector<std::vector<T>>&);
template<typename T>
class Container {
std::vector<T> v;
friend Container<Container<T>> make_double_container<T>(const std::vector<std::vector<T>>&);
public:
Container() {}
explicit Container(std::vector<T> v) : v(v) {}
};
template<typename T>
Container<Container<T>> make_double_container(const std::vector<std::vector<T>>& v) {
Container<Container<T>> c;
for(const auto& x : v) {
c.v.push_back(Container<T>(x));
}
return c;
}
int main() {
std::vector<std::vector<int>> v{{1,2,3},{4,5,6}};
auto c = make_double_container(v);
return 0;
}
編譯器告訴我說:
main.cpp: In instantiation of 'Container<Container<T> > make_double_container(const std::vector<std::vector<T> >&) [with T = int]':
main.cpp:27:37: required from here
main.cpp:8:20: error: 'std::vector<Container<int>, std::allocator<Container<int> > > Container<Container<int> >::v' is private
std::vector<T> v;
^
main.cpp:20:9: error: within this context
c.v.push_back(Container<T>(x));
我相信這是正確的,因爲make_double_container
是Container<T>
的朋友,但不是Container<Container<T>>
。我該如何讓make_double_container
在這種情況下工作?
問題在理論上是有趣的。但是載體的載體是邪惡的,所以它主要是擊敗了目的。 – Drop