c++ - 是否可以使用 SFINAE/模板来检查运算符是否存在?

标签 c++ templates sfinae

我正在尝试在编译时检查运算符是否存在,如果不存在,我只想忽略它,有什么办法吗?

示例运算符:

 template <typename T>
 QDataStream& operator<<(QDataStream& s, const QList<T>& l);

最佳答案

我最终使用了一个后备命名空间:

namespace operators_fallback {
template <typename T>
inline QDataStream& operator<<(QDataStream& s, const T &) { return s; }

template <typename T>
inline QDataStream& operator>>(QDataStream& s, T &) { return s; }

template <typename T>
inline QDebug operator<<(QDebug d, const T &) { return d; }
};

...
inline void load(QDataStream & s) {
    using namespace operator_fallback;
    s >> item;
}

还找到了在编译时检查运算符的正确方法(尽管我将使用后备命名空间)。

或多或少基于这个:

namespace private_impl {
    typedef char yes;
typedef char (&no)[2];

struct anyx { template <class T> anyx(const T &); };

no operator << (const anyx &, const anyx &);
no operator >> (const anyx &, const anyx &);


template <class T> yes check(T const&);
no check(no);

template <typename StreamType, typename T>
struct has_loading_support {
    static StreamType & stream;
    static T & x;
    static const bool value = sizeof(check(stream >> x)) == sizeof(yes);
};

template <typename StreamType, typename T>
struct has_saving_support {
    static StreamType & stream;
    static T & x;
    static const bool value = sizeof(check(stream << x)) == sizeof(yes);
};

template <typename StreamType, typename T>
struct has_stream_operators {
    static const bool can_load = has_loading_support<StreamType, T>::value;
    static const bool can_save = has_saving_support<StreamType, T>::value;
    static const bool value = can_load && can_save;
};
}
template<typename T>
struct supports_qdatastream : private_impl::has_stream_operators<QDataStream, T> {};

template<typename T>
struct can_load : private_impl::has_loading_support<QDataStream, T> {};

template<typename T>
struct can_save : private_impl::has_saving_support<QDataStream, T> {};

template<typename T>
struct can_debug : private_impl::has_saving_support<QDebug, T> {};

//edit 稍微改变了 has_stream_operators。

//edit删除了链接,显然该网站有一些攻击javascript。

关于c++ - 是否可以使用 SFINAE/模板来检查运算符是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4434569/

相关文章:

c++ - 错误 : request for member 'display' in 'square' , 属于非类类型 'GameBoxes::Box<double>()'

C++20 概念要求运算符重载结合用户定义模板运算符重载函数

c++ - SFINAE 启用非模板成员函数

c++ - 我可以在控制流语句中使用 SFINAE 测试吗?

c++ - 为什么我的 SFINAE 表达式不再适用于 GCC 8.2?

c++ - 来自 std::basic_string 的私有(private)继承

c++ - 快速定点 pow、log、exp 和 sqrt

c++ - 尝试将文本文件加载到动态分配的二维数组时出现 'Segmentation fault' 错误

c++静态方法和模板中的继承与重载

c++ - C++ 中查找子数组的模板函数