簡體   English   中英

constexpr成員函數與C ++中的std :: vector數據成員

[英]constexpr member function with std::vector data member in C++

我試圖在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] )。

由於vectorstruct A不是文字類型 ,因此其非靜態成員函數不能是constexpr

所以GCC在C ++ 11模式下拒絕代碼是正確的。

C ++ 14 刪除了這個限制。

C ++ 11的解決方案是聲明dimensions() static

  static constexpr size_t dimensions()
  {
    return n;
  }

現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM