【问题标题】:C++ Template container with two template param, storing in template class's field具有两个模板参数的 C++ 模板容器,存储在模板类的字段中
【发布时间】:2017-05-17 02:10:17
【问题描述】:
template<class TNodeValue>
struct Node
{
    Node* next;
    TNodeValue value; //need to store here TPair<typename Tkey, typename Tvalue>. Got C2512 error: no appropriate default consturctor available.
    Node();
    Node(TNodeValue _value);
};
template<typename TNodeValue>
Node<TNodeValue>::Node()
{
    next = NULL;
    value = NULL;
}
template<typename TNodeValue>
Node<TNodeValue>::Node(TNodeValue _value)
{
    next = NULL;
    value = _value;
}

T配对码:

template <typename Tkey, typename Tvalue>
struct TPair
{
    Tkey key;
    Tvalue value;

    TPair(Tkey _key, Tvalue _value)
    {
        key = _key;
        value = _value;
    }

};

调用错误的代码:

TPair<int, int> a(1, 2);
Node<TPair<int, int> > node(a);

问题是为什么它不会被存储?为什么 TNodeValue 不能存储像 TPair 这样的东西?得到 C2512 错误。 重要提示:不要使用标准库。

【问题讨论】:

  • 这个“问题”毫无意义。你的问题是什么
  • 我已经更新了帖子。现在更清楚了吗?
  • 不,您还没有提出问题,并且没有足够的上下文来说明您在说什么。
  • 问题是为什么 TPair 不会被存储?为什么TNodeValue不能存储TPair之类的东西?
  • @АлександрТрифонов 试试ru.stackoverflow.com

标签: c++ templates containers


【解决方案1】:

TPair&lt;int, int&gt; 没有默认构造函数,因此Node&lt;TPair&lt;int, int&gt;&gt; 构造函数格式错误,因为它们都试图调用此类型的默认构造函数。

Node 默认构造函数需要节点,因为您没有构造函数参数来构造 value 成员,但其他构造函数应使用初始化列表来构造 value

// From C++11 and on, do this:
template<typename TNodeValue>
Node<TNodeValue>::Node(TNodeValue && _value)
    : next(nullptr), value(std::forward(_value)) { }

// Before C++11, do this:
template<typename TNodeValue>
Node<TNodeValue>::Node(TNodeValue const &_value)
    : next(0), value(_value) { }

即使你有value = _value;,由于你不使用初始化列表,代码要求默认构造value成员,然后从_value复制分配value --由于value的类型没有默认构造函数,所以这个Node构造函数无法实例化。

您还可以考虑将默认构造函数添加到TPair

【讨论】:

  • >"您也可以考虑为 TPair 添加一个默认构造函数。"它有效..我无法想象为什么,因为我没有使用这个构造函数,我没有通过这个构造函数创建任何 var。谢谢,先生。
  • 让我们这样说:对于未在构造函数的初始化列表中指定的任何成员,这些成员都是隐式默认构造的。这意味着您只需通过不在 Node 构造函数的初始化程序列表中初始化它来调用 Node 的 value 成员的默认构造。
猜你喜欢
  • 2016-11-07
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
  • 2011-07-26
  • 1970-01-01
  • 1970-01-01
  • 2011-10-01
  • 1970-01-01
相关资源
最近更新 更多