未初始化为布尔C++
Uninitialized to Boolean C++
我正在构造一个模板结构,我需要一些技巧来执行以下操作:
我有一个单维和二维链表,我需要首先构造每个没有数据的节点,然后我必须用文件中的数据填充它们。所以我需要if(x == UNINITIALIZED OR NOT)
,因为数据可以是字符串、整数和双精度。如果检查,我找不到一个通用的空初始化器。我希望有一种方法可以做到这一点。
我尝试了if(x == NULL)
,if(x == 0)
,if(x == "")
,if(x == void)
。他们都没有工作。
如果您的节点表示指定的类型之一,则可以简单地使用模板、模板专用化或重载。
如果只有这三种类型,则可以为已知类型创建专用的初始值设定项函数。
template <class T>
class CNode {
public:
CNode() {
Init(m_Value);
}
private:
T m_Value;
static void Init(T n) { n = 0; } // Default catch for types that can be set to 0/NULL
static void Init(bool b) { b = false; }
static void Init(string str) { str = ""; }
};
当然,也有为模板化函数指定类型细节的方法,但我不记得了。 我知道 Boost 使用这些方法,这将是在原始定义之外指定其他初始化方法的一种方式。
据我了解您的问题,我认为以下代码显示了使用两个 Boost 库的可能且有趣的解决方案:可选和元组:
#include <cassert>
#include <algorithm>
#include <iterator>
#include <list>
#include <string>
#include <boost/optional.hpp>
#include <boost/tuple/tuple.hpp>
int main()
{
typedef boost::tuple<std::string, double, int> value_t;
typedef boost::optional<value_t> node_t;
std::list<node_t> nodes;
// first construct every node with no data in them
std::fill_n(std::inserter(nodes, nodes.begin()), 5, node_t());
// check all nodes have not been initialized yet, so they are in "null" state
auto it = nodes.cbegin();
while (it != nodes.cend())
{
assert(!it->is_initialized());
++it;
}
// add non-null initialized node
// or fill with the data from a file, etc.
node_t n("abc");
nodes.insert(it, n);
assert(nodes.back().is_initialized());
}
相关文章:
- 一个关于在C++中重载布尔运算符的问题
- 提升精神:解析布尔表达式并简化为规范范式
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 线程之间的布尔停止信号
- 布尔比较运算符是如何在C++中工作的
- 变量定义到C++布尔值转换
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 隐式常量/非常量运算符布尔
- 如何编写一个使用n倍三元条件语句的C++布尔函数
- 如何在 c++ 中让布尔变量返回为 0 或 1 而不是真或假?
- 重载更少,则运算符返回相反的布尔值
- 将布尔变量添加到 int
- 为什么布尔开关语句有编译器警告?
- 将此布尔值传递给此函数的最有效方法是什么?
- 如何使布尔变量仅在设置为 true 时才为真?
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 程序中的布尔函数返回输入的范围无论如何都是无效的
- 当我尝试通过 arduino 上的引用传递布尔数组时出现问题
- 如何设置 c++ 类的布尔值?
- 使用 MAKEWORD / MAKEWPARAM 使用布尔值而不是布尔值