假设我正在编写一个用于单链表的迭代器和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时具有两个版本。可能吗?如果是-那么该怎么做?
我不认为只能编写一次函数。您可以使用自动和模板执行大多数操作,但是问题是函数本身的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;
}