【发布时间】:2013-11-17 07:03:22
【问题描述】:
带有位掩码的数组非常流行,通常它们编写起来很乏味,而且它们使代码的可读性降低,我想用constexpr 生成它们,这是我的尝试
#include <iostream>
#include <cstdint>
#include <vector>
#include <utility>
typedef uint32_t myT;
template <typename T>
constexpr std::vector<T> vecFarm(T &&lower, T &&upper, T &&step) {
// std::cout << lower << " " << upper << " " << step << "\n";
std::vector<T> v;
if (lower < upper) {
for (T count = lower; count < upper; count += step) {
v.push_back(count);
};
}
return (v);
}
int main() {
std::vector<myT> k(std::move(vecFarm(myT(0), ~(myT(0)), myT(256)))); //why
// this doesn't work ?
// std::vector<myT> k(std::move(vecFarm(myT(0), ((~(myT(0))) >> 16), myT(256))));
// but this one works
// let's see what we got
for (const auto &j : k) {
std::cout << j << " ";
}
std::cout << "\n";
return (0);
}
我使用了std::move,未命名的对象和constexpr,这段代码编译得很好
g++-4.8 -O3 -std=c++11 -pthread -Werror -Wall -Wextra
但由于bad_alloc,它在运行时失败,我可以看到我的“小”应用程序分配了大量空间。
也许错误很大,我看不到,但为什么这不起作用?
为什么我的应用程序在运行时进行分配?不应该在编译时计算所有内容吗?我期待这可能会在编译时而不是在运行时失败。
【问题讨论】: