0

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

我有一个单维和二维链表,我需要首先构造每个没有数据的节点,然后我必须用文件中的数据填充它们。所以我需要if(x == UNINITIALIZED OR NOT),因为数据可以是字符串、整数和双精度。如果检查,我找不到一个通用的空初始化器。我希望有办法做到这一点。

我试过了if(x == NULL),,,,。他们都没有工作。if(x == 0)if(x == "")if(x == void)

4

3 回答 3

0

如果您的节点代表指定的类型之一,您可以简单地使用模板、模板特化或重载。

于 2012-04-28T22:23:31.673 回答
0

如果您只有这三种类型,则可以为已知类型创建专门的初始化函数。

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 使用这些,这将是一种在原始定义之外指定其他初始化方法的方法。

于 2012-04-29T00:22:06.160 回答
0

据我了解您的问题,我认为以下代码显示了使用两个Boost库的可能且有趣的解决方案:OptionalTuple

#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());
}
于 2012-04-29T00:41:49.273 回答