c++ - MSVC 静态常量模板成员初始化失败

标签 c++ visual-c++ c++11

在使用 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/

相关文章:

c++ - g++ 不会在 Snow Leopard 下编译 std=c++0x

c++ - 将 nullptr 转换为 bool

c++ - 平衡二叉搜索树 (BST)

c++ - 警告 : disabled use of C++11 features in Armadillo

c++ - Arduino 没有读取适当数量的字节

c++ - 如何在 C++ 中的同一个 dll 中获取 dll 位置路径?

visual-c++ - 警告MSB8012 : TargetPath(C:\wxWidgets-2.9.1\build\wx291_msw_vc10\..\..\lib\vc_lib\wxregex.lib) does not match

c++ - 没有堆的 static const std::vector<char> 初始化?

c++ - binary > T 未定义此运算符或转换为预定义运算符可接受的类型

c++ - 这是 MSVC 中依赖名称解析的错误吗?