#include <iostream>
using namespace std;
class S {
public:
S(int a , int b)
{
i = a+b;
}
template<class T>
friend void init (T t,const S& s = S() )
{
cout<<s.i<<endl;
}
private:
int i;
};
void main()
{
S s(10, 40);
double d = 0;
char c = 0;
init( d, s);
}
类里可以嵌套模版友元函数,但是一定要给友元一个理由来推导出T, 例如init(d, s) , 或者直接显式指定init<double>(...)
#include <iostream>
using namespace std;
class S {
public:
S(int a , int b)
{
i = a+b;
}
S()
{
i = 0;
}
public:
int i;
};
template<class T>
void init (T const& t = T())
{
cout<<t.i<<endl;
}
void main()
{
S s(10, 40);
init<S>( );
init(s);
}
当模版函数的参数提供默认参数,并且是默认构造函数构造的对象时,类S也必须提供默认构造函数
++++++++++
但如果是init(s), 那么可以去掉默认构造函数 T() is invalid for T=S, but the default
// call argument T() needs no instantiation
// because an explicit argument is given
#include <iostream>
using namespace std;
class S {
public:
S(int a , int b)
{
i = a+b;
}
public:
int i;
};
template<class T>
void init (T const& t = T())
{
cout<<t.i<<endl;
}
void main()
{
S s(10, 40);
init(s);
}