c++ 如何在MSVC中允许更高的模板递归限制?

20jt8wwn  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(88)

我正在用C++编写模板元编程代码,以生成用于嵌入式编程目的的查找表(缺少FPU)。我一直在使用MSVC进行原型设计。
当尝试生成最终的128x128,每个单元格2字节的LUT时,我得到错误C1202:递归类型或函数依赖上下文太复杂。
但是对于100x100,它在几秒钟内生成,一切都很好。我还没能在网上找到如何在MSVC中增加模板递归限制。
根据2014年的这个问题,问同样的事情,Visual C++ - Set the depth of template instantiation,没有,但我希望事情已经改变了,这里的人可能知道这件事。
下面是上下文的代码:

const size_t tableSize = 128;
const float unit = 80.;
using Cell = std::pair<uint8_t, uint8_t>;

constexpr auto f = [](uint8_t x, uint8_t y) -> Cell {
    float _x = x / unit;
    float _y = y / unit;

    float norm2 = std::sqrt(_x * _x + _y * _y);
    float norm2Min1 = norm2 < 1 ? 1 : norm2;
    return {(uint8_t)(x / norm2Min1), (uint8_t)(y / norm2Min1) };
};

template<uint8_t rowNo, uint8_t columnNo> struct Row {
    Cell cell = f(columnNo, rowNo);
    Row<rowNo, columnNo + 1> rest;
};
template<int rowNo> struct Row<rowNo, tableSize-1> {
    Cell cell = f(tableSize-1, rowNo);
};

template<int rowNo> struct Table {
    Row<rowNo, 0> row;
    Table<rowNo + 1> rest;
};
template<> struct Table<tableSize-1> {
    Row<tableSize-1, 0> row;
};

struct LUT {
    Table<0> table;

    Cell precomputedF(uint8_t x, uint8_t y) {
        return ((Cell*)(&table))[y * tableSize + x];
    }
};

int main()
{
    LUT lut;
    int size = sizeof(LUT);

    std::cout << size << "\n\n";

    for (int x = 0; x < tableSize; x++) {
        for (int y = 0; y < tableSize; y++) {
            auto result = lut.precomputedF(x, y);
            std::cout << "(" << (int)result.first << "," << (int)result.second << ")" << " ";
        }
        std::cout << "\n";
    }
}
k4aesqcs

k4aesqcs1#

不要使用模板。使用constexpr

using Table = std::array<std::array<Cell, tableSize>, tableSize>;
consteval Table make_LUT() {
    Table table;
    for(size_t x=0; x<tableSize; x++) {
        for(size_t y=0; y<tableSize; y++)
            table[y][x] = f(x,y);
    }
    return table;
};
constexpr Table LUT = make_LUT();
constexpr Cell precomputedF(uint8_t x, uint8_t y) {
    return LUT[y][x];
}

http://coliru.stacked-crooked.com/a/0d406313f9bec451
如果您真的想坚持使用更接近原始代码的代码,那么可以简单地使用std::make_integer_sequence<uint8_t,tableSize>()来消除模板中的递归。它的最大深度为2,而不是2xtableSize。我还没有完全弄清楚创建最大深度为1的表的语法,但我怀疑这是可能的。

template<uint8_t row, std::uint8_t... columns>
constexpr TableRow makeTableRow(std::integer_sequence<uint8_t,columns...>) {
  TableRow t = {{f(columns,row)...}};
  return t;
};
template<std::uint8_t tableSize, std::uint8_t... rows>
constexpr Table makeTable(std::integer_sequence<uint8_t,rows...>) {
  Table t = {{makeTableRow<rows>(std::make_integer_sequence<uint8_t,tableSize>())...}};
  return t;
};
constexpr Table lut = makeTable<tableSize>(std::make_integer_sequence<uint8_t,tableSize>());

http://coliru.stacked-crooked.com/a/345718b3818c2231

相关问题