One*_*One 13 c++ templates sfinae
我正在尝试检查运算符是否在编译时存在,如果不存在我只是想忽略它,有没有办法做到这一点?
示例运算符:
template <typename T>
QDataStream& operator<<(QDataStream& s, const QList<T>& l);
Run Code Online (Sandbox Code Playgroud)
One*_*One 12
我最终使用了一个回退命名空间:
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;
}
Run Code Online (Sandbox Code Playgroud)
还找到了在编译时检查运算符的正确方法(尽管我将使用fallback命名空间).
或多或少基于此:
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> {};
Run Code Online (Sandbox Code Playgroud)
//编辑改变了has_stream_operators.
//编辑删除了链接,显然该网站有一些攻击javascript.
| 归档时间: |
|
| 查看次数: |
3944 次 |
| 最近记录: |