在阅读了如何使这些std :: function参数明确无误后,我完全糊涂了?到目前为止,我认为我理解函数模板的部分排序是什么,但在阅读了这个问题后,我写了三个例子来检查编译器的行为,并且收到的结果很难让我理解.
template <class T>
void foo(T) {}
template <class T>
void foo(T&) {}
int main()
{
int i;
foo<int>(i); // error: call is ambiguous!
}
Run Code Online (Sandbox Code Playgroud)
问题:这两个功能都是可行的,这是显而易见的,但不是那个T&比专业更专业的功能T?相反,编译器会引发模糊的调用错误.
#include <iostream>
template <class T>
struct X {};
template <>
struct X<int>
{
X() {}
X(X<int&> const&) {} // X<int> is constructible from X<int&>
// note: this is not a copy constructor!
};
template <>
struct X<int&> …Run Code Online (Sandbox Code Playgroud) c++ templates partial-ordering language-lawyer overload-resolution
我想知道是否有人知道为什么下面的示例没有编译给出过载函数错误的模糊调用.如果我用强类型仿函数签名替换auto,那么它就能够正确地区分两个方法重载.
我注意到当不使用std :: function作为我的重载参数时不会发生同样的问题.如果我的重载只是一个简单的float和int,那么即使使用auto关键字来定义我的输入参数,编译器也可以正确区分这两个重载.我在VisualStudio 2012中编译它.这可能只是VS编译器中的一个错误吗?我现在无法访问带有GCC或Clang的机器,但有人知道这是否会在那里编译?
编译错误:对重载函数的模糊调用
class AmbiguousOverload
{
public:
static void OverloadedMethod(std::function<int()>) {}
static void OverloadedMethod(std::function<float()>) {}
};
int _tmain(int argc, _TCHAR* argv[])
{
auto func1 = []() -> float {
return 0.5f;
};
auto func2 = []() -> int {
return 12;
};
AmbiguousOverload::OverloadedMethod(func1);
AmbiguousOverload::OverloadedMethod(func2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译
class AmbiguousOverload
{
public:
static void OverloadedMethod(std::function<int()>) {}
static void OverloadedMethod(std::function<float()>) {}
};
int _tmain(int argc, _TCHAR* argv[])
{
std::function<float()> func1 = []() -> float {
return 0.5f;
}; …Run Code Online (Sandbox Code Playgroud)