我遇到了一个问题,我已将其归结为以下问题,其中==
即使应该失败,运算符用法也会编译(C++17,在 GCC 5.x、8.x 和 9.x 上测试):
template <int N> struct thing {
operator const char * () const { return nullptr; }
bool operator == (const thing<N> &) const { return false; }
};
int main () {
thing<0> a;
thing<1> b;
a == b; // i don't want this to compile, but it does
}
它进行编译的原因是编译器选择这样做:
(const char *)a == (const char *)b;
而不是这个:
// bool thing<0>::operator == (const thing<0> &) const
a.operator == (b);
因为后者不匹配,因为b
is a thing<1>
not a thing<0>
。 (顺便说一下,它还产生unused-comparison
使用原始比较运算符时发出警告;没什么意思,但这就是出现这些警告的原因。)
我已经验证了这一点(实际上这就是我发现原因的方式)C++ 见解 https://cppinsights.io/,输出:
template <int N> struct thing {
operator const char * () const { return nullptr; }
bool operator == (const thing<N> &) const { return false; }
};
/* First instantiated from: insights.cpp:7 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
struct thing<0>
{
using retType_2_7 = const char *;
inline operator retType_2_7 () const
{
return nullptr;
}
inline bool operator==(const thing<0> &) const;
// inline constexpr thing() noexcept = default;
};
#endif
/* First instantiated from: insights.cpp:8 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
struct thing<1>
{
using retType_2_7 = const char *;
inline operator retType_2_7 () const
{
return nullptr;
}
inline bool operator==(const thing<1> &) const;
// inline constexpr thing() noexcept = default;
};
#endif
int main()
{
thing<0> a = thing<0>();
thing<1> b = thing<1>();
static_cast<const char *>(a.operator const char *()) == static_cast<const char *>(b.operator const char *());
}
显示最后一行中的转换运算符用法main
.
我的问题是:当然,如果我显式地显示转换运算符,整个事情就会正常运行,但是我真的很想保留隐式转换运算符and让编译器强制正确使用operator ==
(其中“正确”= 如果参数类型不同则无法编译)。这可能吗?
请注意,它是not对我来说很重要thing<N> == const char *
工作。也就是说,我不需要这个重载:
bool thing<N>::operator == (const char *) const
所以我不在乎解决方案是否会破坏这种味道==
.
我确实在这里搜索了其他帖子;有一些具有误导性的相似标题,但最终却毫无关联。看起来像这个帖子 https://stackoverflow.com/questions/36392600/binary-operator-overloading-implicit-type-conversion had a related问题(不需要的隐式转换),但它仍然不适用。
为了完整起见,这里有一个稍微不那么简单但更具代表性的示例,说明我实际上正在做的事情,其目的是允许==
为之工作thing<T,N>
and thing<R,N>
, 那就是N
必须相同,但第一个模板参数可以不同。我将其包括在内,以防它影响可能的解决方案,因为这是我真正需要正确行为的:
template <typename T, int N> struct thing {
operator const char * () const { return nullptr; }
template <typename R> bool operator == (const thing<R,N> &) const { return false; }
};
int main () {
thing<int,0> i0;
thing<float,0> f0;
thing<int,1> i1;
i0 == f0;
f0 == i0;
i0 == i1; // should fail to compile
f0 == i1; // should fail to compile
i1 == i0; // should fail to compile
i1 == f0; // should fail to compile
}