【发布时间】:2012-01-27 18:06:22
【问题描述】:
以下代码在 Visual Studio 下编译得很好,但 gcc 4.6.2 或 4.7 都无法处理它。它似乎是有效的,但 gcc 似乎无法解决 const 和非 const 参数之间的区别。这可能是编译器错误吗?
struct CReadType{};
struct CWriteType{};
template<typename ReadWriteType, typename T>
struct AddPkgrConstByType {};
template<typename T>
struct AddPkgrConstByType<CReadType, T> {
typedef T type;
};
template<typename T>
struct AddPkgrConstByType<CReadType, const T> {
typedef T type;
};
template<typename T>
struct AddPkgrConstByType<CWriteType, T> {
typedef T const type;
};
template<typename Packager, typename T>
struct AddPkgrConst : public AddPkgrConstByType<typename Packager::CReadWriteType, T> {
};
template<typename Packager, typename T>
inline bool Package( Packager* ppkgr, T* pt )
{
return true;
}
template<typename Packager>
inline bool Package( Packager* ppkgr, typename AddPkgrConst<Packager,bool>::type* pb)
{
return false;
}
struct ReadPackager {
typedef CReadType CReadWriteType;
};
struct WritePackager {
typedef CWriteType CReadWriteType;
};
int main(int argc, char* argv[])
{
ReadPackager rp;
WritePackager wp;
bool b = true;
const bool cb = false;
Package( &rp, &b );
}
编译器调用:
g++ -fPIC -O -std=c++0x -Wno-deprecated -D_REENTRANT
g++-D__STDC_LIMIT_MACROS -c test.cpp
test.cpp: In function ‘int main(int, char**)’:
test.cpp:58:22: error: call of overloaded ‘Package(ReadPackager*, bool*)’ is ambiguous
test.cpp:58:22: note: candidates are:
test.cpp:31:6: note: bool Package(Packager*, T*) [with Packager = ReadPackager, T = bool]
test.cpp:38:6: note: bool Package(Packager*, typename AddPkgrConst<Packager, bool>::type*) [with Packager = ReadPackager, typename AddPkgrConst<Packager, bool>::type = bool]
【问题讨论】:
-
+1 获取完整的最小示例程序
-
@Mr.Anubis :标准规定了重载解析的工作方式,因此它不应该依赖于编译器。
-
@ildjarn 我弄错了,谢谢 :)
-
@Mr.Anubis :我不确定——你说“如果你有第二个参数类型指针指向
typename AddPkgrConst<Packager, bool>::type,那么重载可能会选择第二个 " 但问题是,在这种情况下,typename AddPkgrConst<Packager, bool>::type解析为bool,这 是 正在传递的内容,所以我对你得到的内容感到困惑。
标签: c++ templates gcc compiler-construction gcc4