有没有办法找出一个类是否有重载运算符

Is there a way to find out if a class has an overloaded operator?

本文关键字:一个 是否 运算符 重载 有没有      更新时间:2023-10-16

>我正在编写一个模板类,我需要一种方法将元素类打印到stdout中。但是我在编写它时遇到了问题 - 如果cout <<operator const char*()在我的元素类中没有定义或重载怎么办?

有没有办法找出它可能会抛出异常而不会得到编译错误?

如果运算符未重载,则程序无法编译。这是一个编译时错误,无法将其延迟到运行时。

解决方法是不使用运算符,而是使用函数指针。如果不支持该操作,则可以将函数指针设置为 0,您可以在运行时检测到该指针。

class A {
public:
    int q; // some data
    typedef std::function<void(std::ostream& os, const A&)> PrinterFunc;
    PrinterFunc func;
    friend std::ostream& operator<<(std::ostream& os, const A& a) {
        if(!a.func) {
            throw "Not supported";
        }
        func(os,a);
        return os;
    }
};
A a;
a.func = [](std::ostream& os, const A& a) { os << "hello " << a.q; }
std::cout << a << std::endl; // will print
A b;
std::cout << b << std::endl; // will throw

此示例使用 C++11 和 <functional> 。对于 C++03,您必须使用"普通"函数指针。

您可以使用一些 SFINAE 来测试是否存在(格式化的)输出运算符:

#include <iostream>
// HasFormattedOutput
// ============================================================================
namespace HasFormattedOutput {
    namespace Detail
    {
        struct Failure{};
    }
    template<typename OutputStream, typename T>
    Detail::Failure operator << (OutputStream&, const T&);
    template<typename OutputStream, typename T>
    struct Result : std::integral_constant<
        bool,
        ! std::is_same<
            decltype(std::declval<OutputStream&>() << std::declval<T>()),
            Detail::Failure
        >::value
    > {};
} // namespace HasFormattedOutput
template <typename T, typename OutputStream = std::ostream>
struct has_formatted_output : std::conditional<
    HasFormattedOutput::Result<OutputStream, T>::value,
    std::true_type,
    std::false_type>::type
{};
// Test
// ============================================================================
struct X {};
int main() {
    std::cout.setf(std::ios_base::boolalpha);
    std::cout << has_formatted_output<const char*>() << 'n';
    std::cout << has_formatted_output<X>() << 'n';
}

(C++11)

相关文章: