【发布时间】:2021-11-29 17:04:44
【问题描述】:
我目前正在练习 ->* 运算符,目的是编写智能指针。我已经完成了它如何工作的基础知识。对于这个例子,我想在使用 operator->*() 时使用模板,这样我就可以将成员函数用于各种返回和参数类型。
以下是我的目标的一个简单示例
Functor.h
#pragma once
#include "RecordCard.h"
template <class OBJECT_TYPE, typename POINTER_TO_MEMBER>
class Functor{
public:
Functor(OBJECT_TYPE* pObj, POINTER_TO_MEMBER pMF):m_pObj(pObj),m_pMF(pMF){}
template <typename RETURN_TYPE>
RETURN_TYPE operator() const
{
return (m_pObj->*m_pMF)();
}
template <typename PARAM_TYPE>
void operator()(PARAM_TYPE param)
{
(m_pObj->*m_pMF)(param);
}
private:
OBJECT_TYPE* m_pObj;
POINTER_TO_MEMBER m_pMF;
};
RecordCard.h
#pragma once
#include "Functor.h"
#include <string>
template <class T, typename U>
class Functor;
class RecordCard{
public:
RecordCard(){}
void SetName(std::string);
void SetAge(unsigned int);
void SetActiveStatus(bool);
std::string GetName() const;
unsigned int GetAge() const;
bool GetActiveStatus() const;
// Other methods of the class
template <typename T>
Functor<RecordCard,T> operator->*(T pmf)
{
return Functor<RecordCard,T>(this, pmf);
}
template <typename T, typename U = T (RecordCard::*)() const>
const Functor<RecordCard,U> operator->*(U pmf) const
{
return Functor<RecordCard,U>(this, pmf);
}
private:
std::string m_szName;
unsigned int m_nAge;
bool m_bActive;
};
RecordCard.cpp
// Method definitions here
// RecordCard::operator->* definition removed from her
// and placed in the header file. Because to otherwise
// causes the linker to complain.
现在问题出在我的主要问题上。 Main.cpp
#include "RecordCard.h"
#include "Functor.h"
int main()
{
RecordCard mycard;
(mycard->*&RecordCard::SetAge)(30); // Works Okay
(mycard->*&RecordCard::GetAge)(); Error??
return 0;
}
编译器给我的两个抱怨是:
无法为 RecordCard::GetAge() const 找到匹配的签名。
无法创建 Functor 的实例
它发生的原因不是调用 operator->*() const。
不使用 lambdas 或 std::function,这些都是为了将来的练习。如何解决此问题以使其正常工作。
非常感谢。
【问题讨论】:
标签: c++ templates operator-overloading overload-resolution pointer-to-member