是否可以使用单个定义同时定义const和常规版本的函数? (使用模板,自动,decltype等)

问题描述 投票:0回答:1

假设我正在编写一个用于单链表的迭代器和const_iterator。

假设我有以下课程:

template <typename T>
struct Node
{
    T value;
    Node* next;
}

template <typename T>
struct NodePtr
{
private:
     Node<T>* node;
public:
     T& operator*() { return node->value; }
     const T& operator*() const { return node->value; }

     // Ommitted increment, comparison and so on...
}

class Iterator<T, bool isConst>
{
     private: NodePtr<T> nodePtr;
     using Reference = std::conditional_t<isConst, const T&, T&>;

     Reference operator*() { return *nodePtr; }
     const Reference operator*() const { return *nodePtr; }

     // Ommited
}

我的问题是是否有可能替换行

Reference operator*() { return node->value; }
const Reference operator*() const { return node->value; }

具有单个定义(可能使用模板参数isConst),并且由编译器推导出const说明符吗?当isConst = true时,我想让*成为const T&operator *()const并且在isConst = false时具有两个版本。可能吗?如果是-那么该怎么做?

c++ overloading const template-instantiation
1个回答
0
投票

我不认为只能编写一次函数。您可以使用自动和模板执行大多数操作,但是问题是函数本身的const说明符。我不知道以任何形式将其作为条件。您可以使它始终为const,然后将nodePtr更改为可变值,但这种方法使整个过程失去了意义。您可以通过执行以下操作来停用const_iter的非常量重载

template<bool tmp = isConst, std::enable_if_t<!tmp, char> = 0> // you need the tmp so that the enable_if is dependent
Reference operator*() {
    return *nodePtr;
}
© www.soinside.com 2019 - 2024. All rights reserved.