在VS2012中编译以下代码没有任何问题。
struct Foo
{
typedef int DummyType;
};
template<typename T>
int Bar(T* foo, typename T::DummyType* dummy_ = 0) { return 0; }
template<typename T>
int Bar(T* foo, ...) { return 1; }
template<typename T>
int Bar(typename T::DummyType* dummy_ = 0) { return 2; }
template<typename T>
int Bar(...) { return 3; }
void fn()
{
Bar((Foo*)NULL);
Bar((int*)NULL);
Bar<Foo>();
Bar<int>();
}
但尝试 VS2013RC 时出现以下错误。这是 VS2013RC 错误还是代码本身的问题。标准对匹配重载函数与模板函数特化和可变参数函数的描述。
1>c:\users\dummy\documents\visual studio 2013\projects\test\test.cpp(25): error C2668: 'Bar' : ambiguous call to overloaded function
1> c:\users\dummy\documents\visual studio 2013\projects\test\test.cpp(15): could be 'int Bar<Foo>(T *,...)'
1> with
1> [
1> T=Foo
1> ]
1> c:\users\dummy\documents\visual studio 2013\projects\test\test.cpp(12): or 'int Bar<Foo>(T *,Foo::DummyType *)'
1> with
1> [
1> T=Foo
1> ]
1> while trying to match the argument list '(Foo *)'
1>c:\users\dummy\documents\visual studio 2013\projects\test\test.cpp(28): error C2668: 'Bar' : ambiguous call to overloaded function
1> c:\users\dummy\documents\visual studio 2013\projects\test\test.cpp(21): could be 'int Bar<Foo>(...)'
1> c:\users\dummy\documents\visual studio 2013\projects\test\test.cpp(18): or 'int Bar<Foo>(Foo::DummyType *)'
1> while trying to match the argument list '()'
谢谢你的帮助!
感谢你的回答!
我刚刚做了一个新的测试如下:
struct Foo
{
typedef int DummyType;
};
// Bar0 #0
template<typename T>
static int Bar0(const T* foo, typename T::DummyType* dummy_) { return 0; }
// Bar0 #1
template<typename T>
static int Bar0(const T* foo, ...) { return 1; }
template<typename T, typename U>
struct DummyType2 {};
// Bar1 #2
template<typename T>
static int Bar1(const T* foo, DummyType2<T, typename T::DummyType>* dummy_) { return 2; }
// Bar1 #3
template<typename T>
static int Bar1(const T* foo, ...) { return 3; }
void fn()
{
std::cout<<Bar0((Foo*)NULL, NULL)<<std::endl; // call 0 matches Bar0 #0
std::cout<<Bar1((Foo*)NULL, NULL)<<std::endl; // call 1 matches Bar1 #3
}
输出是
0
3
为什么调用 0 匹配 Bar0 #0,但调用 1 匹配 Bar1 #3。标准中的任何规则?