ein*_*ica 1 c++ templates overloading boost-any
Boost <boost/any.hpp>有:
template<typename ValueType>
ValueType any_cast(any & operand);
template<typename ValueType>
inline ValueType any_cast(const any & operand);
Run Code Online (Sandbox Code Playgroud)
(以及其他变体.)这种组合不应该导致诸如boost::any_cast<int>(my_any);?之类的调用模糊不清吗?
我问,因为如果我写这个程序:
#include <boost/any.hpp>
#include <iostream>
template<typename ValueType>
ValueType any_cast(boost::any & operand)
{
return boost::any_cast<ValueType>(operand);
}
int main()
{
int x = 123;
boost::any my_any(x);
std::cout << "my_any = " << any_cast<int>(my_any) << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我确实抱怨模糊不清:
g++ -std=c++14 -O3 -Wall -pedantic -pthread main.cpp && ./a.out
main.cpp: In function 'int main()':
main.cpp:14:57: error: call of overloaded 'any_cast(boost::any&)' is ambiguous
std::cout << "my_any = " << any_cast<int>(my_any) << "\n";
^
main.cpp:5:11: note: candidate: ValueType any_cast(boost::any&) [with ValueType = int]
ValueType any_cast(boost::any & operand)
^~~~~~~~
In file included from main.cpp:1:0:
/usr/local/include/boost/any.hpp:281:22: note: candidate: ValueType boost::any_cast(const boost::any&) [with ValueType = int]
inline ValueType any_cast(const any & operand)
^~~~~~~~
/usr/local/include/boost/any.hpp:258:15: note: candidate: ValueType boost::any_cast(boost::any&) [with ValueType = int]
ValueType any_cast(any & operand)
^~~~~~~~
Run Code Online (Sandbox Code Playgroud)
为什么电话会不明确?你调用函数的方式是any参数是左值.因此,any参数将被const限定,在这种情况下,第二个重载是唯一的潜在匹配,或者它const不合格,在这种情况下,第一个重载是更好的匹配(当第二个重载需要转换时不需要转换从any&到any const&).如果用临时函数调用函数any,它可以绑定到rvalue重载(即取出any&&),或者,如果不存在,它可以绑定到const-qualified重载而不是非const限定的重载,同样,不造成任何歧义.
实际上,这里发生了一些有趣的事情:没有全局命名空间中的重载,使用显式模板参数的函数不能被使用!但是,只要存在任何功能模板,即使是不匹配的功能模板,也可以使用它!这是一个例子:
namespace foo {
struct bar {};
template <typename T> void bar_cast(bar&) {}
template <typename T> void bar_cast(bar const&) {}
template <typename T> void bar_cast(bar&&) {}
}
struct whatever;
template <typename T> void bar_cast(whatever);
int main()
{
foo::bar b;
bar_cast<int>(b);
}
Run Code Online (Sandbox Code Playgroud)