【发布时间】:2021-11-02 01:04:23
【问题描述】:
我正在尝试编写一个仅对 std::vector 或 std::list 中的数字进行排序的程序 我为此做了两个概念:
template<typename T>
concept ValidContainer = requires(T a) {
std::same_as<T, std::vector<typename T::value_type>>;
std::same_as<T, std::list<typename T::value_type>>;
};
还有:
template<typename T>
concept Sortable = requires(T a) {
ValidContainer<T> && std::same_as<typename T::value_type, int>;
ValidContainer<T> && std::same_as<typename T::value_type, float>;
};
以及对它们进行排序的函数的签名:
void BubbleSort(Sortable auto& collection)
{
// sort algorithm
}
我脑海中出现的问题是,当我传递std::vector<std::string> 时,它没有显示编译错误?
int main()
{
std::vector<int> test = { 32, 3, 6, 8, 2, 5, 0, 43, 67, 1 };
std::vector<std::string> test2 = { "first", "second", "third" };
BubbleSort(test); // this is ok
BubbleSort(test2); // shouldn't this be a compile error?
return 0;
}
【问题讨论】:
-
为什么是这两个容器?为什么不是特定类型的范围?
-
如果它会检查值,
T不能是std::vector<U>和std::list<U>。
标签: c++ templates c++20 sfinae c++-concepts