我正在尝试在编译时检查运算符是否存在,如果不存在,我只想忽略它,有什么办法吗?
示例运算符:
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/