我试图在C ++类中实现一个constexpr成员函数,它返回一个模板参数。代码应该是c ++ 11兼容的。但是,当模板化的类还包含STL容器作为数据成员(例如std :: vector(constexpr成员函数未触及)时,我会遇到编译问题)。
以下代码给出了一个最小的例子:
#include <vector>
#include <iostream>
#include <array>
template<size_t n>
struct A
{
constexpr size_t dimensions() const
{
return n;
}
private:
std::vector<double> a;
};
int main(int argc,char ** argv)
{
auto a=A<3>();
std::array<double,a.dimensions()> arr;
}
代码使用命令正确编译
g ++ -std = c ++ 14 -O3 quickTest.cpp -o test -Wall
clang ++ -std = c ++ 11 -O3 quickTest.cpp -o test -Wall
但是当我使用时失败了
g ++ -std = c ++ 11 -O3 quickTest.cpp -o test -Wall
有错误
quickTest.cpp:22:33: error: call to non-‘constexpr’ function ‘size_t A<n>::dimensions() const [with long unsigned int n = 3; size_t = long unsigned int]’
std::array<double,a.dimensions()> arr;
~~~~~~~~~~~~^~
quickTest.cpp:10:20: note: ‘size_t A<n>::dimensions() const [with long unsigned int n = 3; size_t = long unsigned int]’ is not usable as a ‘constexpr’ function because:
constexpr size_t dimensions() const
^~~~~~~~~~
quickTest.cpp:22:33: error: call to non-‘constexpr’ function ‘size_t A<n>::dimensions() const [with long unsigned int n = 3; size_t = long unsigned int]’
std::array<double,a.dimensions()> arr;
~~~~~~~~~~~~^~
quickTest.cpp:22:33: note: in template argument for type ‘long unsigned int’
为什么代码不能用gcc -std=c++11
编译但是用clang++ -std=c++11
编译?怎么可以让这个代码片段与旧版本的gcc一起使用,许多人不支持c ++ 14/17,但只支持c ++ 11?
我正在使用gcc 8.1.1和clang 6.0.1
C ++ 11有一个规则[dcl.constexpr]/8:
...该函数所属的类应为文字类型([basic.types])。
由于struct A
,vector
不是文字类型,因此它的非静态成员函数不能是constexpr
。
所以GCC在C ++ 11模式下拒绝代码是正确的。
C ++ 14 removed那种限制。
C ++ 11的解决方案是声明dimensions()
static
:
static constexpr size_t dimensions()
{
return n;
}