在使用 MSVC 编译器时,在模板类上初始化静态常量变量时遇到问题。我试过 MSVC2013、MSVC2012 和 MSVC2010。此代码适用于 MinGW、MinGW-w64、GCC 和 Clang。
#include <iostream>
#include <string>
using namespace std;
template <typename T>
struct StringHolder
{
static const std::string str;
};
template<> const string StringHolder<int>::str { "integer" };
int main()
{
// prints nothing when compiled with MSVC2013, works with MinGW/GCC/Clang
cout << StringHolder<int>::str << endl;
return 0;
}
有什么想法吗?
最佳答案
即使是 MSVC2013 仍然存在统一初始化问题:str { "integer" }
.
要使其与 M$VC 一起使用,请使用原始语法:
template<> const string StringHolder<int>::str = "integer";
template<> const string StringHolder<int>::str("integer");
template<> const string StringHolder<int>::str = {"integer"};
我不确定这里谁更符合标准,GCC 还是 Studio。希望有勇敢的人出现并给我们一个标准条款的链接 ;)
附言至少非模板版本可以正常工作;)
struct StringHolder
{
static const std::string str;
};
const string StringHolder::str{ "integer" };
附言模板化的非专用版本甚至无法编译 ^_^
template <typename T>
struct StringHolder
{
static const std::string str;
};
template <typename T>
const std::string StringHolder<T>::str{ "integer" };
xmemory0(611): error C2143: syntax error : missing ';' before '<end Parse>'
希望他们能在服务包中修复它。
关于c++ - MSVC 静态常量模板成员初始化失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19667568/