gpt4 book ai didi

c++ - 无论实际实例化如何,都接受函数签名中的模板化参数

转载 作者:行者123 更新时间:2023-11-28 00:23:17 25 4
gpt4 key购买 nike

标题可能有点困惑,让我详细说明一下。

说,我有一个类 template<bool is_const> foo可以根据模板参数采用两种形式之一,const 或 non-const。此类有一些运算符重载,例如

bool foo<is_const>::operator==(const foo<is_const> &other) const {
return this->a == other.a;
}

实际的返回值在这里无关紧要。关键是我有很多这样的运算符,对于它们来说,is_const 的值是多少并不重要。用于两个操作数中的任何一个。因此,我想避免重复每个运算符(一次用于 is_bool==true 一次用于 is_bool==false )。是否有可能以一种与什么值无关紧要的方式定义函数 is_bool有?有点像const foo<> &other (这不起作用,我试过了)。

最佳答案

你可以把操作符做成模板:

template <bool B>
bool operator==(const foo<B> & other) const
{
return a = other.a;
}

正如您所发现的,通常最好让运算符重载是非成员函数,可能是友元函数:

template <bool A, bool B>
friend bool operator==(const foo<A> & lhs, const foo<B> & rhs)
{
return lhs.a == rhs.a;
}

关于c++ - 无论实际实例化如何,都接受函数签名中的模板化参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26390922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com