我正在制作一个以类型为模板的项目。正如您所知,运算符==已经为字符,整数,字符串等重载了,但如果用户决定传入一个cstring(空终止字符数组),我将需要重载==。我可以选择仅在用户使用cstrings时重载运算符==,并且当它们不使用时使用默认值==这将如何实现?
答案 0 :(得分:2)
您不能在C字符串上重载==
运算符。我不完全确定为什么这是必要的 - C ++ string
类已经定义了来自C字符串的隐式转换,并且已经定义了==
运算符。
答案 1 :(得分:1)
对于C字符串,您不能重载operator==
,因为它们是指针,如果至少有一个操作数是类或枚举,则运算符可以重载。您可以做的是创建自己的比较器功能并在代码中使用它而不是==
:
template<typename T>
bool my_equal(const T& a, const T& b) {
return a == b;
}
bool my_equal(const char* a, const char* b) {
return /* your comparison implementation */;
}
更新:您可能需要添加更多重载来支持std::string
与const char*
比较,正如TonyD在评论中指出的那样。
答案 2 :(得分:0)
您可以使用类型特征分派到正确的函数。例如:
#include <type_traits>
template<typename T>
using is_cstring =
std::integral_constant<bool,
std::is_same<T, char const*>::value
|| std::is_same<T, char*>::value>;
template<typename T>
class Thingy
{
public:
bool operator==(Thingy const& rhs) const
{
return equal_helper(rhs, is_cstring<T>());
}
private:
bool equal_helper(Thingy const& rhs, std::true_type) const
{
return strcmp(m_value, rhs.m_value) == 0;
}
bool equal_helper(Thingy const& rhs, std::false_type) const
{
return m_value == rhs.m_value;
}
T m_value;
};