鉴于以下代码,模糊性背后的原因是什么?我可以绕过它还是我必须保持(讨厌的)显式演员?
#include <functional>
using namespace std;
int a(const function<int ()>& f)
{
return f();
}
int a(const function<int (int)>& f)
{
return f(0);
}
int x() { return 22; }
int y(int) { return 44; }
int main()
{
a(x); // Call is ambiguous.
a(y); // Call is ambiguous.
a((function<int ()>)x); // Works.
a((function<int (int)>)y); // Works.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有趣的是,如果我a()用function<int ()>参数注释掉函数并a(x)在我的main中调用,则编译正确失败,因为它们之间的类型不匹配x和function<int (int)>唯一a()可用函数的参数.如果编译器在这种情况下失败,为什么在存在这两个a()函数时会有任何歧义?
我试过VS2010和g ++ v.4.5.两者都给我完全相同的歧义.
我定义了一个像这样的方法:
template <class ArgT>
void foo(ArgT arg, ::boost::function< void(ArgT) > func)
{
func(arg);
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用 - 例如 - :
foo(2, [](int i) -> void { cout << i << endl; });
Run Code Online (Sandbox Code Playgroud)
为什么编译器不能推断出类型,因为它肯定是一个int?
我得到'void foo(ArgT,boost::function<void(ArgT)>)' : could not deduce template argument for 'boost::function<void(ArgT)>' from 'anonymous-namespace'::<lambda0>'.
考虑以下代码
#include <functional>
template<class ResultType, class ... Args>
void Foo( std::function<ResultType(Args...)> ) {}
void Dummy(int) {}
int main()
{
Foo<void, int> ( std::function<void(int)>( Dummy ) ); // OK, no deduction and no conversion
Foo( std::function<void(int)>( Dummy ) ); // OK, template argument deduction
Foo<void, int>( Dummy ); // Compile error
}
Run Code Online (Sandbox Code Playgroud)
在第三个中,我知道不能进行模板推导,这就是明确指定模板参数的原因。但是为什么没有从void (*)(int)to的显式转换std::function<void(int)>?
我查找了答案,但这些是关于模棱两可的重载解决方案或模板推论,而不是相关主题。
std::function 的模板参数(签名)不是其类型的一部分吗?
然后我尝试使用我自己的模板类而不是 std::function 进行测试。
// Variadic template class
template<class ... T>
class Bar
{ …Run Code Online (Sandbox Code Playgroud) c++ templates variadic-functions implicit-conversion variadic-templates