获取临时数组的地址时出错(lambda数组)

时间:2016-09-30 03:24:42

标签: c++ arrays lambda

所以,我有一个类,它的构造函数接受一个整数,一个整数向量和一个lambda函数数组,如下所示:

class Cell {
private:
    short m_State;
    std::function< bool(const char) > m_func;

public:
    Cell(short state, std::function< bool(const char) > func) { m_State = state; m_func = func; };
    Cell() { m_State = 0; m_func = [] (char) -> bool { return false; }; };
    bool operator() (const char input) { return m_func(input); };
    short State() { return m_State; };
};


class Row {
private:
    Cell * m_Cells;
    short m_States;

public:
    Row( short num_states, std::vector<short> states, std::function< bool(char) > * funcs ) {
        m_States = num_states;
        m_Cells = new Cell[num_states];
        for (short i = 0; i < m_States; i++) {
            m_Cells[i] = Cell( states[i], funcs[i] );
        }
    };

    ~Row() {
        delete[] m_Cells;
        m_Cells = NULL;
        m_States = 0;
    };

    short operator[] (const char input) const {
        for (short i = 0; i < m_States; i++)
            if (m_Cells[i](input))
                return m_Cells[i].State();
        return -1;
    };
};

现在,假设我有一些lambdas:

auto kIS_BETWEEN = [](char s, char e) { return [s, e](char x) -> bool { return (x >= s && x <= e); }; };
auto kIS_NOT_0_DIGIT_FUNC = kIS_BETWEEN('1', '9')

进一步假设我有这样的预处理器定义:

#define FUNC_TYPE(x) const std::function< bool(const char) >[x]

现在,当我尝试定义Row变量时:

Row x = Row( 1, {1}, (FUNC_TYPE(1)){kIS_NOT_0_DIGIT_FUNC} );

我得到一个&#34;获取临时数组的地址&#34;错误。我做错了什么,我该如何解决?

1 个答案:

答案 0 :(得分:0)

关键是改变我的Row课程,以便:

class Row {
private:
    std::vector<Cell> m_Cells;
    short m_States;

public:
    Row( short num_states, std::vector<short> states, std::vector< std::function< bool(char) > > funcs ) {
        m_States = num_states;
        for (short i = 0; i < m_States; i++) {
            m_Cells.push_back(const Cell( states[i], funcs[i] ));
        }
    };

    short operator[] (const char input) const {
        for (short i = 0; i < m_States; i++)
            if (m_Cells[i](input))
                return m_Cells[i].State();
        return -1;
    };
};