如果类型来自std,是否可以创建特征来回答? [英] Is it possible to create a trait to answer if a type comes from std?

查看:78
本文介绍了如果类型来自std,是否可以创建特征来回答?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ADL在此问题之后如果传递的类型来自我们的命名空间,则可以创建一个特征来回答:

After this question by utilizing ADL one can create a trait to answer if the passed type comes from our namespace:

#include <utility>

namespace helper
{
  template <typename T, typename = void>
  struct is_member_of_sample : std::false_type
  {
  };

  template <typename T>
  struct is_member_of_sample<
      T,
      decltype(adl_is_member_of_sample(std::declval<T>()))> : std::true_type
  {
  };
}

namespace sample
{
  template <typename T>
  auto adl_is_member_of_sample(T && ) -> void;
}

// -- Test it

namespace sample
{
  struct X;
}

struct Y;

static_assert(helper::is_member_of_sample<sample::X>::value, "");
static_assert(not helper::is_member_of_sample<Y>::value, "");

int main(){}

出于明显的原因,无法应用到 std 命名空间-根本没有办法注入与 std等效的 adl_is_member_of_sample 命名空间,而不会暴露于不确定的行为。

From obvious reason this cannot be applied to the std namespace - there is simply no way to inject the adl_is_member_of_sample equivalent to the std namespace without exposing ourself to undefined behaviour.

是否有一些变通办法可以创建特征?

Is there some workaround enabling to create the trait?

推荐答案

这似乎可行:

#include <functional>
#include <type_traits>
#include <utility>
#include <string>

namespace other { struct S{}; }

namespace my {
    template< class Type >
    void ref( Type&& ) {}

    template< class Type >
    auto ref_to( Type&& o )
        -> Type&
    { return o; }

    template< class Type >
    constexpr auto is_std_type()
        -> bool
    {
        using std::is_same;
        using std::declval;
        return not is_same< void, decltype( ref( ref_to( declval<Type>() ) ) )>::value;
    }

    struct Blah {};

    constexpr bool int_is_std       = is_std_type<int>();
    constexpr bool blah_is_std      = is_std_type<Blah>();
    constexpr bool other_is_std     = is_std_type<other::S>();
    constexpr bool string_is_std    = is_std_type<std::string>();
};

#include <iostream>
using namespace std;
auto main()
    -> int
{
    cout << boolalpha;
    cout << "int is std = " << my::int_is_std << "\n";
    cout << "blah is std = " << my::blah_is_std << "\n";
    cout << "other is std = " << my::other_is_std << "\n";
    cout << "string is std = " << my::string_is_std << "\n";
}

这篇关于如果类型来自std,是否可以创建特征来回答?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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