0

所以有一个很棒的库叫做OverLoad(链接到可下载的 svn 目录,lib 只是标题)。它可以接受任何类型的函数,并自动决定您调用的是哪一个。它类似于增强功能,但更好。这里有 2 个代码示例(浏览器可以查看 boost svn 一二 。这是我的代码,它没有编译并且基于它们:

#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();
}

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

4

1 回答 1

1

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

Since this library has to rely on the C++ language's overloading capabilities, it too cannot distinguish between the two functions.

于 2011-12-01T21:56:38.673 回答