【问题标题】:Boost Overload strange behaviour.. how `int (int ), int (std::string )` differs from `int (int ), int (std::string ), std::string (std::string)`?Boost Overload 奇怪的行为.. `int (int), int (std::string)` 与 `int (int), int (std::string), std::string (std::string)` 有何不同?
【发布时间】:2011-12-01 21:48:40
【问题描述】:

所以有一个很棒的库叫做OverLoad (link to downloadable svn directory, lib is header only)。它可以接受任何类型的函数,并自动决定您调用的是哪一个。它类似于增强功能,但更好。 这里有2个代码示例(浏览器可以查看boost svn)onetwo。这是我的代码,它没有编译并且基于它们:

#include <string>

#include <boost/detail/lightweight_test.hpp>

#include <boost/overload.hpp>

using boost::overload; 

template<class out, class in>
out foo(in O )
{
    std::cout << "yes we can!";
    return out();
}

int main()
{
    //// works
    //overload<int (int ), int (std::string )> f;
    //// works
    //int (*foo1) (int ) = &foo<int, int>;
    //int (*foo2) (std::string ) = &foo<int, std::string>;
    //f.set(foo1);
    //f.set(foo2);
    // or we can use
    //// does also work
    //f.set<int (int )>(&foo<int, int>);
    //f.set<int (std::string )>(&foo<int, std::string>);
    ////

    overload<int (int ), int (std::string ), std::string (std::string) > f;
    //// but when we do this
    //f.set<int (int )>(&foo<int, int>);
    //f.set<int (std::string )>(&foo<int, std::string>);
    //f.set<int (std::string )>(&foo<std::string, std::string>);
    //// or this:
    int (*foo1) (int ) = &foo<int, int>;
    int (*foo2) (std::string ) = &foo<int, std::string>;
    std::string (*foo3) (std::string ) = &foo<std::string, std::string>;
    f.set(foo1);
    f.set(foo2);
    f.set(foo3);
    //// we get compile error

    BOOST_ASSERT( f(0) == 1 );
    BOOST_ASSERT( f("hi") == 2 ); // here we get Error  1   error C3066: there are multiple ways that an object of this type can be called with these arguments

    return boost::report_errors();
}

所以我想知道如何解决这个问题?

【问题讨论】:

  • @myWallJSON 我相信你现在已经注意到,以so there is this grate lib XXXX 之类的短语开头的问题在 SO 上并不酷。你能试着在格式化/提出你的问题上付出更多的努力吗?你似乎问了很多,不想付出太多努力使问题变得可口。感谢您的考虑!

标签: c++ boost overloading boost-function


【解决方案1】:

重载解析只考虑参数类型;它不考虑返回类型。因此,在重载解析期间,int (std::string)std::string(std::string) 无法区分。

由于这个库必须依赖 C++ 语言的重载能力,它也无法区分这两个函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 2011-06-07
    • 2017-02-01
    • 2018-01-12
    • 1970-01-01
    • 2010-09-16
    相关资源
    最近更新 更多