Vik*_*tor 3 c++ error-handling templates operator-overloading
我正在编写一个用于改组的模板函数,我想在尝试使用它之前检查'less than'运算符是否在任意数据结构上重载.这有可能吗?
我们可以使用Detection Idiom来测试T < T
编译时是否形成良好.
为了便于阅读,我正在使用experimental :: is_detected,但您可以使用voider模式在C++ 11中自行编写.
首先,它<
是一个良好形成的类:
struct Has_Less_Than{
int value;
};
bool operator < (const Has_Less_Than& lhs, const Has_Less_Than& rhs) {return lhs.value < rhs.value; }
Run Code Online (Sandbox Code Playgroud)
然后是一个不是:
struct Doesnt_Have_Less_Than{
int value;
};
// no operator < defined
Run Code Online (Sandbox Code Playgroud)
现在,对于检测习语部分:我们试图得到"理论"比较结果的类型,然后问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
}
Run Code Online (Sandbox Code Playgroud)
如果你有C++ 17可用,你可以利用constexpr进行测试:
if constexpr(has_less_than<Has_Less_Than>){
// do something with <
}
else{
// do something else
}
Run Code Online (Sandbox Code Playgroud)
它的工作原理是因为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>{});
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
153 次 |
最近记录: |