如何检查类型是否显式/隐式可构造? [英] How to check if type is explicitly/implicitly constructible?

查看:76
本文介绍了如何检查类型是否显式/隐式可构造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查某个类型是否可以从其他类型显式构造(反之亦然)?在这种情况下,有什么SFINAE技巧吗?

How can it be checked that some type is explicitly (or vice versa implicitly) constructible from other type? Is it any SFINAE trick in this situation?

我可以将 is_explicitly_constructible 编写为 std的组合::is_constructible 和 std :: is_convertible :

I can write is_explicitly_constructible as a combination of std::is_constructible and std::is_convertible:

#include <type_traits>

template <typename Type, typename Argument>
struct is_explicitly_constructible
    : std::bool_constant
        <
            std::is_constructible<Type, Argument>::value &&
            !std::is_convertible<Argument, Type>::value
        >
{
};

但是我是否考虑到此类代码中的所有可能情况?

But do I take into account all possible cases in such code?

推荐答案

是的,这是正确的.如果

T ,则可以从参数 A 显式构造 T 类型

Yes, this is correct. A type T is explicitly constructible from an argument A if

  1. 它完全可以从 A 构造.也就是说,假设的 T x(a)是有效的.
  2. 隐式转换格式错误.也就是说,假设函数 T test(){return a;} 格式错误.
  1. It is constructible at all from A. That is, a hypothetical T x(a) is valid.
  2. Implicit conversions are ill-formed. That is, the hypothetical function T test() { return a; } would be ill-formed.

std :: is_constructible 测试#1,而 std :: is_convertible 测试#2的有效性.因此,想要#1而不要#2将是 is_explicitly_constructible ,就像#1和#2将是 is_implicitly_constructible .

std::is_constructible tests #1, and std::is_convertible tests the validity of #2. Hence, wanting #1 and not #2 would be is_explicitly_constructible just as #1 and #2 would be is_implicitly_constructible.

这样的 is_explicitly_constructible / is_implicitly_constructible 对就是您如何实现有条件地 explicit 的构造函数.例如,在libstdc ++中,存在 optional 的以下两个构造函数:

Such an is_explicitly_constructible/is_implicitly_constructible pair is how you would implement a constructor being conditionally explicit. For instance, in libstdc++, these two constructors for optional exist:

隐式:

 template <typename _Up = _Tp,
            enable_if_t<__and_<
              __not_<is_same<optional<_Tp>, decay_t<_Up>>>,
              is_constructible<_Tp, _Up&&>,   // (*) 
              is_convertible<_Up&&, _Tp>      // (*)
              >::value, bool> = true>
  constexpr optional(_Up&& __t)

explicit :

  template <typename _Up = _Tp,
            enable_if_t<__and_<
              __not_<is_same<optional<_Tp>, decay_t<_Up>>>,
              is_constructible<_Tp, _Up&&>,        // (*)
              __not_<is_convertible<_Up&&, _Tp>>   // (*)
              >::value, bool> = false>
  explicit constexpr optional(_Up&& __t);

您可以看到libstdc ++使用与您相同的表达式.

You can see that libstdc++ uses the same expressions that you do.

这篇关于如何检查类型是否显式/隐式可构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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