通过使返回的obj不变,即使在内部包含非常量数组的情况下,也要在编译时编译constexpr函数?

问题描述 投票:0回答:2
我了解了constexpr函数以及它们何时进行编译时间计算。现在,我必须要用新值填充数组,因此数组不能为const

据我所知,当函数内部的每个值都是constexpr且使用的函数是const时,也肯定只使用constexpr值,因此在编译时肯定会评估const函数。此外,另一篇文章指出,可以通过使返回的obj const来强制进行编译时编译。

可以说,我的函数是constexpr,但是内部有non-const数组,但是返回的对象将是const。我的函数calculation是否在编译时评估(强制?)。

template<int Size, typename T> struct Array{ T array[Size]; Array(const T * a){ for(int i = 0; i < Size; i++){ array[i] = a[i]; } } }; template<typename T, int size> class Example{ private: Array<size, T> _array; public: constexpr explicit Example(T * arr):_array(arr){}; constexpr explicit Example(const T * arr):_array(arr){}; }; template<typename D, int size, typename ...buf, typename T> constexpr auto calculations(const T & myObj){ D test1[2]; // calculation fills arr return Example<D, size>(test1); } int main(){ const int size = 2; const double test1[size] = {1,2}; const auto obj1 = Example<double, size>(test1); //compile time //obj2 calculations during compile time or run-time? const auto obj2 = calculations<double, size>(obj1); }

我了解了constexpr函数以及它们何时进行编译时计算。现在,我必须要用新值填充数组,因此该数组不能为const。据我所知,一个...
c++ compilation constexpr compile-time-constant
2个回答
2
投票
据我所知,当函数内部的每个值均为const且使用的函数为仅使用const值的constexpr时,肯定会在编译时评估constexpr函数。此外,另一篇文章指出,可以通过使返回的obj const来强制进行编译时编译。

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.