相当于Boost has_dereference的C ++ 11 std [英] C++11 std equivalent of Boost has_dereference

查看:82
本文介绍了相当于Boost has_dereference的C ++ 11 std的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多Boost的SFINAE帮助器已经出现在C ++ 11的std库中,但是has_dereference似乎没有.除了此功能之外,我还设法从程序包中消除了Boost依赖性,并且希望完全摆脱它,因此,如何仅使用C ++ 11 std功能获得最佳效果呢?

Many of Boost's SFINAE helpers have appeared in the std library with C++11, but has_dereference doesn't seem to have. Other than this feature, I've managed to eliminate a Boost dependency from my package, and I'd like to get rid of it entirely, so how best to get the same effect using just C++11 std features?

推荐答案

检查类是否具有一些没有外部依赖项的函数的最简单方法通常是使用void_t习惯用语.

The easiest way to check if a class has some function with no external dependencies is generally with the void_t idiom.

// Define this once in your project somewhere accessible
template <class ... T>
using void_t = void;

那把戏总是一样的;您定义了一个从std::false_type继承的类模板:

The trick then is always the same; you define a class template that inherits from std::false_type:

template <class T, class = void>
struct has_dereference : std::false_type {};

这是后备"类模板.现在,我们将定义一个特殊化,该特殊化仅在类型具有所需属性时才起作用:

This is the "fallback" class template. Now we're going to define a specialization that only works when the type has the property we want:

template <class T>
struct has_dereference<T, void_t<decltype(*std::declval<T>())>> : std::true_type {};

要使用,只需执行以下操作:

To use, just do:

bool x = has_dereference<int*>::value;
bool y = has_dereference<int>::value;

从技术上讲,我会补充说,operator*实际上是一个函数系列;该操作员既可以通过CV认证,也可以通过价值类别认证.每当您对类型执行检测时,实际上就是在该系列中进行检测.我不会详细介绍它,因为在实践中很少遇到它(operator*很少是值类别限定的,并且运算符几乎总是具有const版本,而volatile很少出现),但是值得一提的是,当您看到时令人惊讶的事情.

I will add that technically, operator* is actually a family of functions; the operator can be both CV qualified and value category qualified. Whenever you perform detection on a type, you are actually doing detection within this family. I won't get more into details because it's rarely encountered in practice (operator* is rarely value category qualified, and the operator almost always has a const version, and volatile rarely comes up) but it's worth being aware of in case you see something surprising.

该技术值得了解,尤其是当您在没有诸如Boost或Hana之类的依赖项的情况下进行元编程时.您可以在此处了解有关void_t的更多信息: void_t如何工作.

This technique is worth knowing about, especially if you are doing meta-programming without dependencies like Boost or Hana. You can read more about void_t here: How does `void_t` work.

这篇关于相当于Boost has_dereference的C ++ 11 std的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆