【发布时间】:2011-05-16 05:02:00
【问题描述】:
我使用三个不同的文件来定义一个模板类。类声明在.h 文件中,实现在.cpp 文件中,显式实例包含在.inc 文件中。
我正在尝试定义一个朋友函数,它能够访问模板类的私有数据成员。
与模板类的情况一样,函数将在 3 个单独的文件中定义、实现和实例化。
当我尝试调用该函数时,我收到以下错误消息:
myclass.h:error: ‘doSomething’ is neither function nor member function; cannot be declared friend
myclass.h:error: expected ‘;’ before ‘<’ token
mymethod.h: error: ‘friend’ used outside of class
有人对如何解决这个问题有任何建议吗?我试图简化下面的代码。
myclass.h
template<class T>
class MyClass{
friend T doSomething<T>( MyClass<T> *, T, int);
friend MyClass<T> * doSomethingElse<T>( const MyClass<T> *, const MyClass<T> *);
public:
...
private:
T *m_pMyMatrix;
};
mymethod.h
#include <myclass.h>
template <class T> friend T doSomething( MyClass<T> *, T, int);
template <class T> MyClass<T>* doSomethingElse(const MyClass<T>*, const MyClass<T>*);
mymethod.cpp
#include <mymethod.h>
template <class T>
T doSomething( MyClass<T> * pData, T val, int index){
// the actual code does sth. more complex than the code below.
pData->m_pMyMatrix[index]+=val;
return pData->m_pMyMatrix[index];
}
template <class T>
MyClass<T>* doSomethingElse(const MyClass<T> * pData1, const MyClass<T> * pData2){
...
T res1 = doSomething(pData1, val1, index1);
...
}
#include "mymethod-impl.inc"
mymethod-impl.inc
template float doSomething( MyClass<float> *, float, int);
template double doSomething( MyClass<double> *, double, int);
template MyClass<float>* doSomethingElse(const MyClass<float>*, const MyClass<float>*);
template MyClass<double>* doSomethingElse(const MyClass<double>*, const MyClass<double> *);
【问题讨论】:
-
使用好友功能可能很危险!任何人都可以编写具有相同签名的静态函数并获得对您的类的控制权,除非您的朋友函数使用命名空间声明。
-
@Edwin:我想这属于旧的“防止墨菲家伙获得控制权,反正反对马基雅维利是徒劳的”。
-
@sbi:我只是在说明当您使用朋友功能时(您致力于一个已知的可信实体),请确保您的朋友确实是您想要的。猜你想要什么。