类的inline static成员在g++编译正常但clang报错,如何修正?
我有一个简单的C++项目,文件如下:
foo.h
class foo{ inline static const int array[3] = { 1, 2, 3 }; };
foo.cc
#include "foo.h" foo a_foo;
main.cc
#include "foo.h" int main() { foo b_foo; }
使用g++编译:
g++ -c *.cc g++ *.o -o a.out
仅出现警告:
In file included from foo.cc:2:0:
foo.h:2:25: warning: inline variables are only available with -std=c1z or -std=gnu1z
inline static const int array[3] = { 1, 2, 3 };
^~~~~
In file included from main.cc:3:0:
foo.h:2:25: warning: inline variables are only available with -std=c1z or -std=gnu1z
inline static const int array[3] = { 1, 2, 3 };
^~~~~
但使用clang编译,即使加上-std=c++1z参数:
clang -std=c++1z -c *.cc clang -std=c++1z *.o -o a.out
会报错:
In file included from foo.cc:2:
./foo.h:2:1: error: 'inline' can only appear on functions
inline static const int array[3] = { 1, 2, 3 };
^
./foo.h:2:25: error: in-class initializer for static data member of type 'const int [3]' requires 'constexpr' specifier
inline static const int array[3] = { 1, 2, 3 };
^ ~~~~~~~~~~~
constexpr
2 errors generated.
In file included from main.cc:3:
./foo.h:2:1: error: 'inline' can only appear on functions
inline static const int array[3] = { 1, 2, 3 };
^
./foo.h:2:25: error: in-class initializer for static data member of type 'const int [3]' requires 'constexpr' specifier
inline static const int array[3] = { 1, 2, 3 };
^ ~~~~~~~~~~~
constexpr
2 errors generated.
请问如何修正代码使其能在clang中正常编译?
根据clang的报错提示,针对C++17标准(对应编译参数-std=c++1z),只需做一处关键修改:给数组类型的静态成员变量加上constexpr修饰符,结合inline即可满足编译器要求。
修正后的foo.h代码如下:
class foo{ inline static constexpr int array[3] = { 1, 2, 3 }; };
如果需要兼容更早的C标准(比如C11/C++14),可以采用分离声明和定义的方式:
兼容C11/C14的修改方案
foo.h
class foo{ static const int array[3]; };
foo.cc
#include "foo.h" const int foo::array[3] = {1, 2, 3}; foo a_foo;
两种修改方案都能让g和clang正常编译,第一种更适合C17及以上标准的场景,第二种则兼顾旧版本兼容性。
内容的提问来源于stack exchange,提问作者inprocess

