假设我想重载 ostream
的左移运算符s 和所有容器。
这是我目前拥有的(用 -fconcepts
编译):
#include <vector>
#include <iostream>
template<typename Container>
concept bool Iterable = requires(Container t) {
{ *t.begin()++, t.end() };
};
template<Iterable T>
std::ostream& operator<<(std::ostream& out, const T& t) {
for(const auto& it: t) {
out << it << " " ;
}
return out;
}
int main() {
std::vector<int> a = {1, 2, 3};
std::cout << a << std::endl;
std::string str = "something";
// std::cout << str << std::endl; // compile error if the template is defined
return 0;
}
然而,问题在于,这已经是一个版本的 ostream&<<
对于 std::string
.
是否有通用的(类似于 requires not
表达式)或特定的(可能类似于我可以排除具体类的偏特化)方法来排除概念中的某些内容?
如果不是,正确的解决方法是什么?
最佳答案
template<Iterable T>
requires !requires(std::ostream o, T a) { operator<<(o, a); }
std::ostream& operator<<(std::ostream& out, const T& t) {
for(const auto& it: t) {
out << it << " " ;
}
return out;
}
添加一个要求,该类型还没有 operator<<
定义。我不是 100% 确定这应该有效,但它确实适用于 gcc .
(就是 o << a
使 gcc 崩溃)
关于c++ - 缩小 C++ 概念以排除某些类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54912163/