鉴于以下代码,模糊性背后的原因是什么?我可以绕过它还是我必须保持(讨厌的)显式演员?
#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.两者都给我完全相同的歧义.
在C++库头文件中,我们有时会看到以下内容以提高类中代码的易读性:
template<typename MyExplicitelyLongTemplateParameter>
class C
{
public:
typedef MyExplicitelyLongTemplateParameter P;
// Use "P" and keep your sanity.
};
Run Code Online (Sandbox Code Playgroud)
我的问题是,可以用模板模板参数做同样的事吗?
template<template<typename> typename MyExplicitelyLongTemplateParameter>
class C
{
public:
typedef /* ??? */ P;
// Use "P" and keep your sanity.
};
Run Code Online (Sandbox Code Playgroud)