检查T是否具有运算符<<

时间:2020-02-19 13:31:41

标签: c++17

我正在编写代码以与各种类型的实例进行比较。最终的比较功能非常简单-具有签名:

template <typename T>
int not_equal(const T& arg1, const T& arg2) {
    if (arg1 == arg2)
        return 0;

    std::cerr << "Error when comparing" << std::endl;
    return 1;
}

现在-我想将在std::cerr消息中进行比较的实际值添加为:

std::cerr << "Error when comparing " << arg1 << " != " << arg2 << std::endl;

但是-许多类没有operator<<-可以。对于不支持operator<<的类,我只需要类名-即伪代码应类似于:

if (supports_operator<<<T>)
    std::cerr << "Error when comparing " << arg1 << " != " << arg2 << std::endl;
else
    std::cerr << "Error when comparing instances of type: " << typeid(arg1).name() << std::endl;

我可以使用虚拟的supports_operator<<<T>()功能吗?

编辑:我仅限于C ++ 17

1 个答案:

答案 0 :(得分:0)

如果您能够使用C ++ 20和concepts,则可以执行以下操作:

#include <iostream>
#include <concepts>

template <typename T> 
concept Streamable = requires (T x) { std::cout << x; };

struct Foo {};
struct Bar {};

std::ostream& operator<<(std::ostream& os, Foo const& obj) {
    // write obj to stream
    return os;
}

template <Streamable T>
void foo(T const& t) {
    std::cout << t << std::endl;
}

int main() {
    Foo f;
    Bar b;

    foo(f);
    foo(b); // error

    return 0; 
}

Demo

相关问题