作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用三个不同的文件来定义一个模板类。类声明在 .h
中文件,在 .cpp
中实现文件和显式实例包含在 .inc
中文件。我正在尝试定义一个友元函数,它能够访问模板类的私有(private)数据成员。与模板类的情况一样,函数将在 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
有人对如何解决这个问题有什么建议吗?我试图简化下面的代码。
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;
};
#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>*);
#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"
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> *);
最佳答案
我觉得应该可以
template<class T>
class MyClass;
template <class T>
T doSomething( const MyClass<T> *, T, int);
template<class T>
class MyClass {
friend T doSomething<T>( const MyClass<T> *, T, int);
public:
...
private:
T *m_pMyMatrix;
};
也就是说,您需要先声明模板,然后才能使其(或其实例)成为 friend 。
关于c++ - 在模板类中定义友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4285826/
我是一名优秀的程序员,十分优秀!