在MSVC和GCC上声明和初始化constexpr的通用语法

Common syntax for declaring and initializing constexpr on MSVC and GCC

本文关键字:constexpr 语法 声明 MSVC GCC 初始化      更新时间:2023-10-16
namespace MyNS {
    template <>
    class Test<Test1> {
        public:
            constexpr static char const *description[] = { "X`", "Y1"};
        /*
        ...
        ...
        */
    } 
    constexpr char const * Test<Test1>::description[]; 
    /* Above definition is required when compiling with GCC but MSVC compiler gives error saying 'description' is redeclared.  */
    /* **Omitting definition of 'description', which is written outside class in namespace, causes successful compilation by MSVC but failure in GCC** */ 
}

是否有一种通用的方法来定义、声明和初始化上面的constexpr,使得代码在MSVC和GCC下都能成功编译?

代码:

#include <iostream>
namespace MyNS {
    template<class T> struct Test;
    template <>
    struct Test<int> {
        constexpr static char const * description[] = { "X1", "Y1"};
    };
}
int main() {
    std::cout << MyNS::Test<int>::description[0];
    return 0;
}

编译-据我所知-使用

  • g++-4.8+ -std=c++11
  • g++-4.8+ -std=c++1y
  • g++-4.9+ -std=c++14
  • g++-6.1+
  • g++-6.1+ -std=c++11
  • g++-6.1+ -std=c++14

没有进一步的定义(其中4.8+表示从g++版本4.8开始及以后)。