gpt4 book ai didi

c++ - Boost Overload 奇怪的行为.. `int (int ), int (std::string )` 与 `int (int ), int (std::string ), std::string (std::string)` 有何不同?

转载 作者:行者123 更新时间:2023-11-28 08:13:42 26 4
gpt4 key购买 nike

所以有一个很棒的库叫做 OverLoad (link to downloadable svn directory, lib is header only) .它可以接受任何类型的函数并自动决定你调用的是哪一个。它就像 boost 功能,但更好。这里有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();
}

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

最佳答案

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

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

关于c++ - Boost Overload 奇怪的行为.. `int (int ), int (std::string )` 与 `int (int ), int (std::string ), std::string (std::string)` 有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8348754/

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