我想实现一些整数常量,这些常量依赖于使用模板特化的一些其他整数常量,例如
//main.cpp
#include<cstdint>
template <uint64_t D> struct space_per_element { static const uint64_t bits; };
template <> const uint64_t space_per_element<2>::bits = 1;
int main() {
return space_per_element<2>::bits;
}
使用
进行编译g++ -std=c++11 main.cpp
但是一旦我试图像这样拆分它。
//constants.hpp
#include<cstdint>
template <uint64_t D> struct space_per_element { static const uint64_t bits; };
//constants.cpp
#include "constants.hpp"
template <> const uint64_t space_per_element<2>::bits = 1;
//main.cpp
#include "constants.hpp"
int main() {
return space_per_element<2>::bits;
}
使用它编译它。
g++ -std=c++11 main.cpp constants.cpp
我收到以下错误:
main.cpp: In function ‘int main()’:
main.cpp:4:11: error: ‘space_per_element’ was not declared in this scope
return space_per_element<2>::bits;
^
main.cpp:4:31: error: ‘::bits’ has not been declared
return space_per_element<2>::bits;
^
constants.cpp:3:45: error: expected initializer before ‘<’ token
template <> const uint64_t space_per_element<2>::bits = 1;
有趣的是,代码与
一起使用g++ -std=gnu++11 main.cpp constants.cpp
或
clang -std=c++11 main.cpp constants.cpp
我现在的问题是:这里使用了哪个GNU扩展?代码是否违反了标准?如果是:如何仅使用标准在多个文件中实现此代码?如果Clang似乎支持相同的代码,那么从可移植性的角度来看,使用GNU++11
会被视为不良做法吗?
答案 0 :(得分:1)
在同一目录中似乎有一些预编译的头文件与其他代码不兼容。删除它们(rm *.gch
)后,我能够使用g++ -std=c++11 main.cpp constants.cpp
编译文件。
看来,两个工作选项都有效,因为它们没有使用这些预编译的头文件。