所以有一个很棒的名为OverLoad (link to downloadable svn directory, lib is header only)的lib。它可以接受任何类型的功能,并自动决定你呼叫哪一个。它就像提升功能但更好。 以下是2个代码示例(浏览器可以查看boost svn)one two。这是我的代码,它不编译并基于它们:
#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();
}
所以我想知道如何解决这个问题?
答案 0 :(得分:1)
重载分辨率仅考虑参数类型;它不考虑返回类型。因此,在重载解析期间,int (std::string)
与std::string(std::string)
无法区分。
由于这个库必须依赖于C ++语言的重载功能,所以它也无法区分这两个函数。