【发布时间】:2016-09-25 10:29:37
【问题描述】:
在处理一些旧代码时,它遇到了一个std::unique_ptr<bool>,用于存储一些布尔值(在类构造函数中分配并用作数组)。
当我试图用std::vector<bool> 替换它时,我遇到了一个问题,我不得不调用一个库函数,该函数接受一个计数和一个指向第一个布尔值的指针 (const bool*):有一个模板专门化std::vector<bool> 将 8 个布尔值压缩到一个字节中,因此如果不先解压缩,就无法获得指向数据的 bool* 指针。
我已经通过 Google 搜索或 StackOverflow 文章 C++11 vector<bool> performance issue (with code example) 找到了一些解决方案,但它们都不适合我(即使用包含布尔值的结构会起作用,但这会使我尝试简化的代码更加复杂; std::valarray 不提供 data() 成员)
还有一篇文章“How to prevent specialization of std::vector<bool>”,但所有解决方案都只是变通方法,我不相信“bool 和 unsigned char 通常自己占用相同数量的内存”这句话(在compiler error when pointing to an element of std::vector<bool>? 中提到)
我还检查了Alternative to vector<bool>,但我们没有在我们的解决方案中使用 boost,我也不愿意添加这个依赖项以供一次性使用。
我的问题是:有没有办法忽略模板特殊化并显式使用未特殊化的模板作为类型?
例如
#include <iostream>
template<class T>
class MyTemplate
{
public:
static const int Value = 0;
}
template<>
class MyTemplate<double>
{
public:
static const int Value = 1;
};
int main(int argc, char **argv)
{
// How can I make MyTemplate<double> ignore the spezialization and output 0?
std::cout << "0==" << MyTemplate<double>::Value << std::endl;
return 0;
}
【问题讨论】:
-
将书包装在某个结构中并从那里继续如何?
-
那是“标准”解决方案,但要使用库调用,我需要一个 reinterpret_cast 并且在读取或写入项目时,我需要访问结构的值成员,否则我必须在结构中实现自动装箱/拆箱,这使得它变得复杂。
-
拥有布尔值数组的方法有很多,但绕过
vector<bool>特化不是其中之一。 -
等价于
std::unique_ptr<bool>将是unique<bool>。std::vector<bool>将用于std::unique_ptr<bool[]>... -
是的,这就是我要更改此代码的原因之一。 (你确定你打算写
unique<bool>而不仅仅是bool?)
标签: c++ templates pointers c++11 vector