gpt4 book ai didi

c++ - 无法解析模板委托(delegate)中重载的类方法

转载 作者:行者123 更新时间:2023-11-30 03:09:37 24 4
gpt4 key购买 nike

背景:我正在使用委托(delegate)技术抽象化对任意对象方法的访问,但我在链接器方面遇到了一些问题。考虑以下类(class),ContextNode .

template <class ObjectType, class GetType, class SetType>
class ContextNode: public ContextNodeBase {
public:
ContextNode(ObjectType* target,
GetType (ObjectType::*getter)(void),
void (ObjectType::*setter)(const SetType& ref)
): _target(target), _getter(getter), _setter(setter) { }

virtual ~ContextNode(void) { }

virtual void r(Datum& value) {
value = (_target->*_getter)();
return;
}

virtual void w(const Datum& value) {
(_target->*_setter)(value);
return;
}

private:
ObjectType* _target;
GetType (ObjectType::*_getter)(void);
void (ObjectType::*_setter)(const SetType& ref);
};

执行Datum无关紧要。还要考虑普通类 Thing .

class Thing {
public:
Thing(void);
~Thing(void);

int getValue(void) { return _value; }
void setValue(const int& x) { _value = x; }
private:
int _value;
};

问题:我可以构建 ContextNode 的实例化像这样。

Thing* thing = new Thing();
ContextNode<Thing,int,int>* cn = new ContextNode<Thing,int,int>(thing, &Thing::getValue, &Thing::setValue);

这很适合我的需要。不过,我遇到了重载方法的问题。假设我改写了:

class Thing {
public:
Thing(void);
~Thing(void);

int value(void) { return _value; }
void value(const int& x) { _value = x; }
private:
int _value;
};

Thing* thing = new Thing();
ContextNode<Thing,int,int>* cn = new ContextNode<Thing,int,int>(thing, &Thing::value, &Thing::value);

链接失败。我认为,问题在于链接器仅尝试基于名称的解析,因此我看到了 <unresolved overloaded function type>错误。

我的问题:是否有一些语法糖可以明确指定我指的是几个重载方法中的哪一个?我无法想象如此愚蠢的怪癖会破坏如此优雅的解决方案。我在网上找不到任何东西,在 C++ FAQ 上也找不到,在 SO 上也找不到关于这个主题的任何东西。

有什么解决办法,还是我被淹没了?

最佳答案

您可以使用强制转换来消除重载函数名称的歧义:

(int (Thing::*)(void))(&Thing::value)
(void (Thing::*)(const int&))(&Thing::value)

关于c++ - 无法解析模板委托(delegate)中重载的类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3946955/

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