C++ 正在初始化链接列表的模板变量

C++ 正在初始化链接列表的模板变量,c++,templates,constructor,initialization,C++,Templates,Constructor,Initialization,我正在创建一个链表类,它使用一个内部链接类和一个模板类来定义可以存储在链表中的类型 然而,在我的方法popValue中,它应该返回模板类型T,我不能初始化默认类型(在本例中称为Point),尽管每个链接中存储的类型都有一个默认构造函数,根据,它指示T retval=T()/T{}应该工作 此外,鉴于T retval不是引用类型,我看不出错误消息是如何对应的 因此,所讨论的方法是: template<typename T> T LinkedList<T>::popValue

我正在创建一个链表类,它使用一个内部
链接
类和一个模板类来定义可以存储在链表中的类型

然而,在我的方法
popValue
中,它应该返回模板类型
T
,我不能初始化默认类型(在本例中称为
Point
),尽管每个链接中存储的类型都有一个默认构造函数,根据,它指示
T retval=T()/T{}
应该工作

此外,鉴于
T retval
不是引用类型,我看不出错误消息是如何对应的

因此,所讨论的方法是:

template<typename T>
T LinkedList<T>::popValue() {
    T retval = T(); //This doesnt work
    Point test = Point(); //But this is allowed?
    if (head != 0) {
        Link *n = head;
        retval = head->value;
        head = head->next;
        delete n;
    }
    return retval;
}
LinkedList.cpp(仅限错误方法)

模板
T LinkedList::popValue(){
T retval=T();//这不起作用
Point test=Point();//但这是
如果(头!=0){
链接*n=头部;
retval=头->值;
头部=头部->下一步;
删除n;
}
返回返回;
}

根据错误消息

引用类型为“点&”

T很可能是引用类型

您可以通过以下方式进行检查:

static_assert(std::is_reference<T>::value == false, "");
如果未声明“x_t”:

#include <type_traits>
int main() {
  using T = int &;
  typename std::remove_reference<T>::type b =
      typename std::remove_reference<T>::type();
  return 0;
}

返回输出参数弹出的元素仍然是一个选项(当列表为空时保持输出参数不变),但是,也许您只是不想存储引用。

但是,我仍然可以将它用于不是
对象的类型吗?您能否提供一个非常简短的答案,说明如何将其用于LinkedList.h/.cpp(只需简单的类描述和构造函数或单个方法即可)?编译器things
LinkedList
正在使用
T=Point&
初始化。那显然不是你想要的。请发布一个@davidhood2您的
popValue
函数将非常混乱,因为如果列表已经为空,它将返回一个完全有效的值。与其在空列表中抛出异常,还不如返回可能被误认为有效值的内容。@PaulMcKenzie通常抛出异常是我选择的选项,但这将被移植到不支持异常的Arduino
static_assert(std::is_reference<T>::value == false, "");
#include <type_traits>
int main() {
  using T = int &;
  std::remove_reference_t<T> b = std::remove_reference_t<T>();
  return 0;
}
#include <type_traits>
int main() {
  using T = int &;
  typename std::remove_reference<T>::type b =
      typename std::remove_reference<T>::type();
  return 0;
}
template<typename T>
T LinkedList<T>::popValue() {
    if (head != 0) {
        Link *n = head;
        T retval = head->value;
        head = head->next;
        delete n;
        return retval;
    } else {
      std::remove_reference_t<T> x = std::remove_reference_t<T>();
      return x; // very bad when T is reference
    }
}