gpt4 book ai didi

c++ - 在模板类中定义友元函数

转载 作者:行者123 更新时间:2023-11-30 02:10:49 28 4
gpt4 key购买 nike

我使用三个不同的文件来定义一个模板类。类声明在 .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

有人对如何解决这个问题有什么建议吗?我试图简化下面的代码。

我的类.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;
};

我的方法.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>*);

我的方法.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"

我的方法实现.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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com