c++ - 缩小 C++ 概念以排除某些类型

标签 c++ templates template-meta-programming c++-concepts

假设我想重载 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/

相关文章:

C++ 编译时条件运行时语句

c++ - 条件断点修饰符查看数组是否已更改

c++ - open() 的参数太多

c++ - 使用新线程复制互斥锁所有权

python - 我怎么会收到这个 Django 错误?

design-patterns - 创建将内容放在不同位置的 Jinja2 宏

c++ - 我怎样才能实现一个通用的最小值?

c++ - 使用 TMP 计算表示值所需的位数

c++ - CMake C/C++宏生成

c++ - 如何在编译时订购类型?