【发布时间】:2021-03-07 19:28:53
【问题描述】:
我正在尝试创建一个概念来检查 std::less 是否有专门化。
在cppreference 上看到 std::hash 的概念示例,我创建了以下代码:
#include <bit>
#include <complex>
#include <concepts>
#include <functional>
#include <iostream>
#include <type_traits>
template < typename DataType >
concept Lessable = requires(DataType value1, DataType value2)
{
{ std::less < DataType > {}(value1, value2) } -> std::convertible_to < bool >;
};
template < typename DataType >
concept Hashable = requires(DataType value)
{
{ std::hash < DataType > {}(value) } -> std::convertible_to < size_t >;
};
// Specialization for std::less < std::complex < float > >.
namespace std
{
template <>
struct less < std::complex < float > >
{
bool operator()(const std::complex < float > &number1, const std::complex < float > &number2) const
{
return number1.real() < number2.real() ||
number1.real() == number2.real() && number1.imag() < number2.imag();
}
};
}
// Specialization for std::hash < std::complex < float > >.
namespace std
{
template <>
struct hash < std::complex < float > >
{
size_t operator()(const std::complex < float > &number1) const
{
return std::hash < float > {}(number1.real()) ^ std::rotl(std::hash < float > {}(number1.imag()), 1);
}
};
}
int main()
{
std::cout << Lessable < std::complex < float > > << "\n";
std::cout << Hashable < std::complex < float > > << "\n";
return 0;
}
出于某种我不明白的原因,Hashable 按预期工作,如果存在专业化,则返回 true;如果专业不存在,则为 false。
但是Lessable 总是返回true,无论是否存在特化。
谁能告诉我我做错了什么以及我必须做些什么来解决这个问题?
谢谢!
【问题讨论】:
-
在
std::complex上进行测试应该归咎于timsong-cpp.github.io/cppwp/n4861/library#namespace.std-2 - 尝试自定义类型。 -
如果你能在你的问题中解释为什么你想这样做 - 你希望通过这些知识实现什么 - 我们也许能够帮助你解决 那个问题以不同的方式。
-
解释我想要达到的目标有点困难......但是,有了 Nicol Bolas 的回答,我想我可以用另一种方式解决我的问题。无论如何,感谢您的关注,凯西!
标签: c++ template-specialization c++-concepts