未初始化为布尔C++

Uninitialized to Boolean C++

本文关键字:C++ 布尔 初始化      更新时间:2023-10-16

我正在构造一个模板结构,我需要一些技巧来执行以下操作:

有一个单维和二维链表,我需要首先构造每个没有数据的节点,然后我必须用文件中的数据填充它们。所以我需要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());
}