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。据我所知,一个...
据我所知,当函数内部的每个值均为const且使用的函数为仅使用const值的constexpr时,肯定会在编译时评估constexpr函数。此外,另一篇文章指出,可以通过使返回的obj const来强制进行编译时编译。