C++ 模板返回带有类型名值的元组
C++ template returning tuple with typename-values
在我实现与 key/value-pairs 一起工作的基于模板的链表的过程中,我想实现一个“popHead()
”方法。但是,我无法编译它。
/**
* Removes the first element in the list and returns it.
* @return first element, nullptr if list is empty
*/
std::tuple<K, V> popHead() {
auto tmp = head;
if (tmp) {
if (tmp->next) {
head = tmp->next;
} else {
head = nullptr;
}
return new std::tuple(tmp->key, tmp->value);
}
return nullptr;
};
这不起作用,因为需要指定类型。好的,所以它不知道元组包含的值应该具有哪种类型......但是......这也不起作用:
return new std::tuple<K, V>(tmp->key, tmp->value);
如何 return 类型为 <K, V>
的元组?
也许
return {tmp->key, tmp->value};
?
或者,也许,您想要 return 指向 std::tuple<K, V>
的 指针 ?
在这种情况下
return new std::tuple<K, V>(tmp->key, tmp->value);
应该可以,但您必须修改 return 类型
std::tuple<K, V> * popHead()
// --------------^ *pointer* to tuple
在我实现与 key/value-pairs 一起工作的基于模板的链表的过程中,我想实现一个“popHead()
”方法。但是,我无法编译它。
/**
* Removes the first element in the list and returns it.
* @return first element, nullptr if list is empty
*/
std::tuple<K, V> popHead() {
auto tmp = head;
if (tmp) {
if (tmp->next) {
head = tmp->next;
} else {
head = nullptr;
}
return new std::tuple(tmp->key, tmp->value);
}
return nullptr;
};
这不起作用,因为需要指定类型。好的,所以它不知道元组包含的值应该具有哪种类型......但是......这也不起作用:
return new std::tuple<K, V>(tmp->key, tmp->value);
如何 return 类型为 <K, V>
的元组?
也许
return {tmp->key, tmp->value};
?
或者,也许,您想要 return 指向 std::tuple<K, V>
的 指针 ?
在这种情况下
return new std::tuple<K, V>(tmp->key, tmp->value);
应该可以,但您必须修改 return 类型
std::tuple<K, V> * popHead()
// --------------^ *pointer* to tuple