Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static const template member initialization fails with MSVC

I have a problem getting static const variable initialized on a templated class when using MSVC-compiler. I have tried MSVC2013, MSVC2012 and MSVC2010. This code works well with MinGW, MinGW-w64, GCC and 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;
}

Any ideas?

like image 965
user4157482 Avatar asked Oct 29 '13 19:10

user4157482


1 Answers

Even MSVC2013 still have problems with uniform initialization: str { "integer" }.

To make it work with M$VC use vanilla syntax:

template<> const string StringHolder<int>::str = "integer";

template<> const string StringHolder<int>::str("integer");

template<> const string StringHolder<int>::str = {"integer"};

I'm not sure who is more standard compliant here, GCC or Studio. Hope some brave man will pop up and will give us a link to standard clause ;)

P.S. At least non-templated version works fine ;)

struct StringHolder
{
    static const std::string str;
};

const string StringHolder::str{ "integer" };

P.P.S. Templated, non-specialized version not even compiles ^_^

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>'

Hope they'll fix it in service pack.

like image 96
Ivan Aksamentov - Drop Avatar answered Nov 04 '22 10:11

Ivan Aksamentov - Drop