C++ 如何在类declaration之外声明泛型类的友元?
下面的代码可以工作,但我想移动ostream&operator使用friend和模板时必须小心C++ 如何在类declaration之外声明泛型类的友元?,c++,templates,generics,friend,C++,Templates,Generics,Friend,下面的代码可以工作,但我想移动ostream&operator使用friend和模板时必须小心 #include<iostream> #include<map> template <class T> class MyHash{ public: // ... use your T template here template <class U> friend ostream& operator<<(ost
#include<iostream>
#include<map>
template <class T>
class MyHash{
public:
// ... use your T template here
template <class U>
friend ostream& operator<<(ostream& out, const MyHash<U> &rhs);
};
// ...
template <class U>
ostream& operator<<(ostream& out, const MyHash<U> &rhs){ return out << "test"; }
#包括
#包括
模板
类MyHash{
公众:
//…在此处使用您的T模板
模板
friend ostream&operator由于这个问题似乎不是完全重复的,我将解释您的程序的功能
template <typename T>
class test {
int private_field;
friend std::ostream& operator<<( std::ostream&, test<T> const & );
};
// ???
int main() {
std::cout << test<int>() << std::endl;
}
现在,如果您查看实例化的模板,您可以注意到friend
声明是对一个非模板函数的友好。因此,在这个特定程序中,您可以使用该特定函数填充?
:
std::ostream& operator<<( std::ostream& o, test<int> const & t ) {
return o << t.private_field;
}
std::ostream&operator请参阅您可能想要查看的副本)。我有一个后续问题:当我使用您的解决方案时,我将函数定义放置在不同于类定义的文件中,我需要在定义中包含.cpp文件,而不是在尝试使用该类时包含.h文件。我在做什么g?就是我所说的一个例子。如果我按原样编译它,一切都没问题,但是如果我在test.cpp中将include hash.cpp更改为hash.h,并使用g++test.cpp hash.cpp进行编译,那么它就不会编译,也不会包含在“hash.h”中,或者阅读我答案中的编辑部分以了解更多细节。
#include<iostream>
#include<map>
template <class T>
class MyHash{
public:
// ... use your T template here
template <class U>
friend ostream& operator<<(ostream& out, const MyHash<U> &rhs);
};
// ...
template <class U>
ostream& operator<<(ostream& out, const MyHash<U> &rhs){ return out << "test"; }
template <typename T>
class test {
int private_field;
friend std::ostream& operator<<( std::ostream&, test<T> const & );
};
// ???
int main() {
std::cout << test<int>() << std::endl;
}
class test<int> {
friend std::ostream& operator<<( std::ostream&, test<int> const & );
};
std::ostream& operator<<( std::ostream& o, test<int> const & t ) {
return o << t.private_field;
}
template <typename T>
class test {
template <typename U>
friend std::ostream& operator<<( std::ostream&, test<U> const & );
};
template <typename T>
std::ostream& operator<<( std::ostream&, test<T> const & ) { ... }
template <typename T> test;
template <typename T> std::ostream& operator<<( std::ostream&, test<T> const & );
template <typename T>
class test {
friend std::ostream& operator<< <T>( std::ostream&, const test<T>& );
};
template <typename T>
std::ostream& operator<<( std::ostream&, test<T> const & ) { ... }