我目前正在阅读一本关于模板的书,它给出了以下示例:
#include <string>
// note: reference parameters
template <typename T>
inline T const& max (T const& a, T const& b)
{
return (a < b) ? (b) : (a);
}
int main()
{
char* a="apple";
char* p="peach";
::max(a,p); // OK, BUT
::max("apple","peach");// <<<< ERROR IN VISUAL STUDIO 2012, WHY?
}
我不明白为什么 VS2012 说:
error C2440: 'return' : cannot convert from 'const char *' to 'const char (&)[6]'
有人可以给我解释一下吗? 书上说这个应该可以,不过是老书了,还在等新的。
最佳答案
问题是在第二种情况下,您 T const&
被推断为 const char(&)[6]
,这是对数组的引用6 个字符。
在 VS2012 中,当您使用 ?:
进行比较时,它会将数组引用衰减到 char*
,这样就无法将其作为引用返回. GCC 4.7.2 没有表现出这种衰减(参见 https://ideone.com/yIBZWi )。
你能试试下面的不太紧凑的版本吗(我手头没有 VS2012)?它应该能够通过在返回中不一起使用 a 和 b 来避免衰减。
template <typename T>
inline T const& max (T const& a, T const& b)
{
if(a<b)
return b;
else
return a;
}
关于Visual Studio 2012 的 C++ 模板问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17322517/