我正在编写一个用于改组的模板函数,我想在尝试使用它之前检查’less than’运算符是否在任意数据结构上重载.这有可能吗? 我们可以使用检测成语来测试T T在编译时很好地形成. 为了
首先,它适用于一个<形成良好:
struct Has_Less_Than{
int value;
};
bool operator < (const Has_Less_Than& lhs, const Has_Less_Than& rhs) {return lhs.value < rhs.value; }
然后是一个不是:
struct Doesnt_Have_Less_Than{
int value;
};
// no operator < defined
现在,对于检测习语部分:我们尝试获取“理论”比较结果的类型,然后询问is_detected:
template<class T>
using less_than_t = decltype(std::declval<T>() < std::declval<T>());
template<class T>
constexpr bool has_less_than = is_detected<less_than_t, T>::value;
int main()
{
std::cout << std::boolalpha << has_less_than<Has_Less_Than> << std::endl; // true
std::cout << std::boolalpha << has_less_than<Doesnt_Have_Less_Than> << std::endl; // false
}
Live Demo
如果您有C 17可用,您可以利用constexpr if进行测试:
if constexpr(has_less_than<Has_Less_Than>){
// do something with <
}
else{
// do something else
}
它的工作原理是因为constexpr if是在编译时计算的,编译器只会编译所采用的分支.
如果您没有可用的C 17,则需要使用辅助函数,可能需要使用标记的调度:
template<class T>
using less_than_t = decltype(std::declval<T>() < std::declval<T>());
template<class T>
using has_less_than = typename is_detected<less_than_t, T>::type;
template<class T>
void do_compare(const T& lhs, const T& rhs, std::true_type) // for operator <
{
std::cout << "use operator <\n";
}
template<class T>
void do_compare(const T& lhs, const T& rhs, std::false_type)
{
std::cout << "Something else \n";
}
int main()
{
Has_Less_Than a{1};
Has_Less_Than b{2};
do_compare(a, b, has_less_than<Has_Less_Than>{});
Doesnt_Have_Less_Than c{3};
Doesnt_Have_Less_Than d{4};
do_compare(c, d, has_less_than<Doesnt_Have_Less_Than>{});
}
Demo
