Friend模板函数(在非模板类中),C ++ [英] Friend template functions (in non-template classes), C++
本文介绍了Friend模板函数(在非模板类中),C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个非模板(即普通)类并希望有一个模板好友函数,那么如何编写它而不会导致编译器错误?下面是一个例子来说明我正在尝试做什么:
template< class T>
void bar(T * ptr);
class MyClass //注意这不是模板类
{
private:
void foo();
模板< class T>
朋友void bar(T *); //错误:编译器给我带来各种悲伤
};
模板< class T>
void bar(T * ptr)
{
if(ptr)
{
MyClass obj;
obj.foo();
}
}
我使用Visual Studio 2005,我收到的错误是 error C2063 ,说酒吧不是一个功能。这里有什么需要改变的地方? 解决方案
您确定您发布的内容会给出错误吗?以下(使用Visual Studio 2005)适用于我:
#include< iostream>
模板< class T>
void bar(T * ptr);
class MyClass //注意这不是模板类
{
private:
void foo();
模板< class T>
朋友void bar(T *); //错误:编译器给我带来各种悲伤
};
void MyClass :: foo()
{
std :: cout<< fooed! <<的std :: ENDL;
}
模板< class T>
void bar(T * ptr)
{
if(ptr)
{
MyClass obj;
obj.foo();
$ b $ int _tmain(int argc,_TCHAR * argv [])
{
int someObj = 1;
bar(&someObj);
返回0;
}
If I have a non-template (i.e. "normal") class and wish to have a template friend function, how do I write it without causing a compiler error? Here is an example to illustrate what I am trying to do:
template <class T>
void bar(T* ptr);
class MyClass // note that this isn't a template class
{
private:
void foo();
template <class T>
friend void bar(T*); // ERROR: compiler gives me all kinds of grief
};
template <class T>
void bar(T* ptr)
{
if (ptr)
{
MyClass obj;
obj.foo();
}
}
I'm using Visual Studio 2005, and the specific error I'm given is error C2063, stating that "bar" isn't a function. What needs to be done differently here?
解决方案
Are you sure what you've posted gives the error? The following (using Visual Studio 2005) works fine for me:
#include <iostream>
template <class T>
void bar(T* ptr);
class MyClass // note that this isn't a template class
{
private:
void foo();
template <class T>
friend void bar(T*); // ERROR: compiler gives me all kinds of grief
};
void MyClass::foo()
{
std::cout << "fooed!" << std::endl;
}
template <class T>
void bar(T* ptr)
{
if (ptr)
{
MyClass obj;
obj.foo();
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int someObj = 1;
bar(&someObj);
return 0;
}
这篇关于Friend模板函数(在非模板类中),C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文