如何处理模板返回

How to deal with template return?

本文关键字:返回 处理 何处理      更新时间:2023-10-16

也许是因为我是一个新人,无法定义它属于哪种问题。所以我搜索后没有找到想要的结果。

这是我的链表实现与C++模板

template<class T> struct Node
{
    T value;
    Node<T>* pre;
    Node<T>* next;
};
template<class T> class Flist
{
    private:
        Node<T>* front;
        Node<T>* end; 
        int count;
    public:
        Flist();   
        ~Flist();
        Flist(const Flist& C_list); 
        inline void Deeply_Copy(const Flist& Copylist);
        bool Isempty() const;
        int Listsize() const;
        Node<T>& Listfront()const;
        Node<T>& Listend() const;
        void push_front(T N);
        void push_back(T N);
        void del_front();
        void del_back();
        Node<T>* Listfind(T x); 
        T ShowKey(int n);   
};

template<class T> T Flist<T>::ShowKey(int n)
{
    if (front == 0)
        {
            cout << "there is no element is the list.." << endl;
            return ???;
        }
    Node<T>* temp = front;
    while(n--)
    {
        temp = temp->next;
    }
    return temp->value;
}

函数 ShowKey(int n( 我希望它返回(而不仅仅是显示(第 n 个元素的值,但如果列表为空,我不知道要返回什么。我不想使用退出来停止该过程。有没有更友好的方法来处理这种情况?

我会将函数签名更改为

bool showKey(int n, T& value);

并使用它来设置 value 变量,如果条目存在于索引 n 处,则返回 true,如果条目不存在,则返回 false(并保持值不变(。

最好的选择可能是抛出异常; std::domain_errorstd::range_error可能合适。