【发布时间】:2021-08-18 17:34:19
【问题描述】:
给定概念test,它有一个接受输入范围的函数。
template <class T>
concept test = requires(T t, archtypes::Input_Range<T> t_range)
{
{ t.count(t_range) } -> std::same_as<int>;
};
此archtype 允许count 函数成为模板成员函数。
struct Counter1
{
template<std::ranges::input_range Range>
int count(const Range&);
}
static_assert(test<Counter1>); // passes
现在这满足了这个概念。但我希望这失败,因为这个范围可以是任何输入范围,而不仅仅是带 int 的输入范围。
只有这样才能通过
struct Counter2
{
template<std::ranges::input_range Range>
requires std::is_same_v<int,std::ranges::range_value_t<Range>>
int count(const Range&);
}
namespace archetypes
{
// private, only used for concept definitions, NEVER in real code
template <class T>
class InputIterator
{
public:
InputIterator();
~InputIterator();
InputIterator(const InputIterator& other);
InputIterator(InputIterator&& other) noexcept;
InputIterator& operator=(const InputIterator& other);
InputIterator& operator=(InputIterator&& other) noexcept;
using iterator_category = std::input_iterator_tag;
using value_type = T;
using reference = T&;
using pointer = T*;
using difference_type = std::ptrdiff_t;
bool operator==(const InputIterator&) const;
bool operator!=(const InputIterator&) const;
reference operator*() const;
InputIterator& operator++();
InputIterator operator++(int);
};
template <class T>
struct Input_Range
{
Input_Range(const Input_Range& other) = delete;
Input_Range(Input_Range&& other) = delete;
Input_Range& operator=(const Input_Range& other) = delete;
Input_Range& operator=(Input_Range&& other) = delete;
~Input_Range();
using iterator = InputIterator<T>;
iterator begin();
iterator end();
};
}
我想不出任何改变概念或架构类型的方法,所以Counter1 会失败,但Counter2 会通过。
【问题讨论】:
标签: c++ templates c++20 c++-concepts std-ranges