简体   繁体   English

c ++ overload:string literal与boost :: function ambiguity

[英]c++ overload: string literal vs. boost::function ambiguity

my problem code: 我的问题代码:

#include <string>
#include <boost/function.hpp>

void func (const std::string&) {}
void func (const boost::function<void()>&) {}

int main() {
    func (main); // good
    func ("bad");
    return 0;
}

=> =>

error: call of overloaded ‘func(const char [4])’ is ambiguous
overload.cpp:4: note: candidates are: void func(const std::string&)
overload.cpp:5: note:                 void func(const boost::function<void ()()>&)

I know I could resolve this by explicitly calling func (string ("bad")); 我知道我可以通过显式调用func(string(“bad”))来解决这个问题。 or by providing a func (const char*), but I wonder if there is a way to keep the caller side as in the example and without introducing more overloads. 或者通过提供一个func(const char *),但我想知道是否有一种方法可以保持调用者方面,如示例中所示,并且不会引入更多重载。

Maybe something with boost::enable_if? 也许是boost :: enable_if的东西? Thanks for any hints. 谢谢你的任何提示。

You can't easily solve this. 你不能轻易解决这个问题。 boost::function<> and std::function<> don't support only functors callable by f() , but also pointer to members callable by (secondArg.*firstArg)() and data members, so their constructors basically slurp everything in, and later decide what to do with the type. boost::function<>std::function<>不仅支持f()可调用的函子,而且还支持可由(secondArg.*firstArg)()和数据成员调用的成员的指针,因此它们的构造函数基本上都会使所有内容都出现问题在,然后决定如何处理该类型。

It's not trivial at all to write such a SFINAE testing class that guards from implicit conversions (and I'm not even sure whether it would be at all possible, since the Standard library doesn't do it. That must have some reason). 编写这样一个防止隐式转换的SFINAE测试类并不是微不足道的(我甚至不确定它是否完全可能,因为标准库没有这样做。这必须有一些原因)。 Remember that a type may be callable because of many different properties - it may have a conversion function to function pointer type etc pp. Writing a SFINAE class that could make this work means to reject an implicit conversion in some cases and accept an implicit conversion in other cases based on really not obvious properties at all. 请记住,由于许多不同的属性,类型可以是可调用的 - 它可能具有转换函数以指示函数指针类型等。编写可以使此工作的SFINAE类意味着在某些情况下拒绝隐式转换并接受隐式转换其他案例基于真正不明显的属性。

If you want to avoid this ambiguity, I would try just choose a different function name or if it's a one-shot problem, do the casting on the caller side. 如果你想避免这种歧义,我会尝试选择一个不同的函数名称,或者如果它是一次性问题,请在调用方面进行转换。

add this: 添加这个:

void func (const char *s) {  func(string(s)); }

update 更新

template<class A0, ...>
void func (const A0 &a0, ...) {
    func(argize(a0), ...); // convert chars to strig, otherwise jut pass
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM