gpt4 book ai didi

c++ - 使用 boost hana 检查特定的嵌套类型/标签

转载 作者:行者123 更新时间:2023-11-30 01:43:07 24 4
gpt4 key购买 nike

享受 boost::hana 带来的乐趣。我希望检查一个特定的嵌套类型,它像另一个类型中的标签一样,所以我借用了 hana::when_valid 示例并定义了一个类 is_S 及其支持 SFINAE 的特化:

#include <iostream>

#include <boost/hana/core/when.hpp>
namespace hana = boost::hana;

#define V(x) std::cout << x << std::endl

struct S_tag { };

struct S {
using tag = S_tag;
};

struct T {
using tag = int;
};

template< typename T, typename = hana::when< true > >
struct is_S {
static constexpr bool value = false;
};

template< typename T >
struct is_S< T, hana::when_valid< typename T::tag > > {
static constexpr bool value = std::is_same<
typename T::tag, S_tag >::value;
};

int main () {
std::cout << "is_S ( S { }) = "; V ((is_S< S >::value));
std::cout << "is_S ( T { }) = "; V ((is_S< T >::value));
std::cout << "is_S (float { }) = "; V ((is_S< float >::value));

return 0;
}

这打印:

$ clang++ -std=c++1z sfinae.cpp && ./a.out | c++filt
is_S ( S { }) = 1
is_S ( T { }) = 0
is_S (float { }) = 0

是否有一种更简单/更短/更简洁的方式来编写相同的支票,以符合 hana 哲学的值(value)类型计算?

最佳答案

下面是我可能会写的:

#include <boost/hana.hpp>
#include <iostream>
namespace hana = boost::hana;


struct S_tag { };
struct S { using tag = S_tag; };
struct T { using tag = int; };

auto tag_of = [](auto t) -> hana::type<typename decltype(t)::type::tag> {
return {};
};

auto is_S = [](auto t) {
return hana::sfinae(tag_of)(t) == hana::just(hana::type<S_tag>{});
};

int main() {
std::cout << "is_S ( S { }) = " << is_S(hana::type<S>{})() << std::endl;
std::cout << "is_S ( T { }) = " << is_S(hana::type<T>{})() << std::endl;
std::cout << "is_S (float { }) = " << is_S(hana::type<float>{})() << std::endl;
}

关于c++ - 使用 boost hana 检查特定的嵌套类型/标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38339136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com