在尝试为字符串文字添加模板特化时,我注意到 VS 2017 编译器和 VS 2010 编译器(均从 VS 2017 调用)之间的行为差异
这是有问题的代码:
#include <iostream>
template <typename T>
struct foo
{
static const int a = -1;
};
template <size_t n>
struct foo<char[n]>
{
static const int a = 0;
};
template <size_t n>
struct foo<const char[n]>
{
static const int a = 1;
};
template <typename T>
int bar(const T& x)
{
#pragma message (__FUNCSIG__)
return foo<T>::a;
}
int main()
{
std::cout << _MSC_VER << '\n';
std::cout << bar("a") << '\n';
}
使用 VS 2017 的默认编译器运行:
int __cdecl bar<char[2]>(const char (&)[2]) 1911 0
并使用 VS 2010 编译器运行:
int __cdecl bar<const char[2]>(const char (&)[2]) 1600 1
如您所见,T
对于旧编译器被推断为 const char[2]
,但对于 char[2]
新的那一个。什么改变了?这是 Visual Studio 中的错误修复/错误,还是在 C++11/C++14 中更改了正确的行为?
尝试使用 tio.run(gcc 和 clang),似乎 VS 2017 是正确的,这是正确的吗?
最佳答案
这是简单的类型匹配。
您的函数采用const T&
。如果我传递一个整数,T
将被推断为 int
,所以签名是 const int&
。将其推导为 const int
只会是多余的。
可以看到,你的参数已经是里面的const了,所以匹配掉了。
肯定是 MSVC 2010 错误,随着时间的推移已经修复,因为旧版本的 visual studio 的模板实现质量非常低。
关于c++ - (Visual-)字符串文字的 C++ 模板类型推断 - VS 2010 与 VS 2017,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46832851/