本文介绍了朋友模板类的模板函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取以下代码工作:
How do I get the following code to work:
#include <array>
#include <iostream>
template<typename T>
class MyClass;
template<typename T, size_t N>
MyClass<T> myFun( const std::array<T, N>& a );
template<typename T>
class MyClass
{
MyClass( size_t n )
{ std::cout << "Ctor with n = " << n << '\n'; }
template<size_t N>
friend MyClass<T> myFun<T, N>( const std::array<T, N>& a );
};
template<typename T, size_t N>
MyClass<T> myFun( const std::array<T, N>& a )
{
return MyClass<T>( N );
}
int main()
{
std::array<int, 3> a;
myFun( a );
return 0;
}
gcc不喜欢 template< size_t N& / code>前面
朋友
声明:
错误:无效使用template-id'myFun '在声明主模板的朋友MyClass myFun(const std :: array& a);
error: invalid use of template-id 'myFun' in declaration of primary template friend MyClass myFun( const std::array& a );
推荐答案
你只需要复制将模板向前声明到
朋友
声明中:
You just need to copy the forward-declaration of the template into your
friend
declaration:
template<typename T>
class MyClass
{
MyClass( size_t n )
{ std::cout << "Ctor with n = " << n << '\n'; }
template<typename T1, size_t N>
friend MyClass<T1> myFun( const std::array<T1, N>& a );
};
这篇关于朋友模板类的模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!