小编gre*_*reg的帖子

constexpr - 函数不能用于常量表达式

我想在编译时为给定范围内的数学函数计算查找表,然后在运行时从表中检索值.我的代码如下:

#include <iostream>
#include <cmath>


template<int size>
class LookupTable {
public:
constexpr LookupTable(double xMin, double xMax) : array(), xMin(xMin), xMax(xMax), dx((xMax - xMin) / (size - 1)) {
    for(auto i = 0; i < size; ++i)
        array[i] = exp(xMin + i * dx);
}

constexpr double operator()(double x) const {
    return array[std::min(std::max(static_cast<int>((x - xMin) / dx), 0), size-1)];
}

private:
double array[size];
double xMin;
double xMax;
double dx;
};



int main() {
    const double x = 0.5;
    constexpr LookupTable<10000> table(0.0, …
Run Code Online (Sandbox Code Playgroud)

c++ g++ cmath constexpr c++14

5
推荐指数
1
解决办法
3162
查看次数

通过引用存储的c ++变体类成员

我正在尝试使用std :: variant.我将std :: variant存储为类的成员.在下面的代码中,如果变量按值存储,则工作正常,但如果变量通过引用存储,则不起作用(对于矢量大小写,也适用于自定义对象).这是为什么?

#include <variant>
#include <vector>
#include <iostream>


template<typename T>
using VectorOrSimple = std::variant<T, std::vector<T>>;


struct Print {
void operator()(int v) { std::cout << "type = int, value = " << v << "\n"; }
void operator()(std::vector<int> v) const { std::cout << "type = vector<int>, size = " << v.size() << "\n"; }
};


class A {
public:
    explicit A(const VectorOrSimple<int>& arg) : member(arg) {
        print();
    }

    inline void print() const {
        visit(Print{}, member);
    }

private:
    const …
Run Code Online (Sandbox Code Playgroud)

c++ boost variant c++17

1
推荐指数
1
解决办法
849
查看次数

标签 统计

c++ ×2

boost ×1

c++14 ×1

c++17 ×1

cmath ×1

constexpr ×1

g++ ×1

variant ×1