简体   繁体   English

如何根据Boost.Hana中的表达式是否有效来过滤类型的元组?

[英]How do I filter a tuple of types depending on whether an expression is valid in Boost.Hana?

In a reduced example I have two types with in a tuple and I want to create another tuple that only contains the types where an expression is valid (in this example I'm using the + operator). 在一个简化的示例中,我在一个元组中有两种类型,我想创建另一个仅包含表达式有效的类型的元组(在此示例中,我使用+运算符)。

My attempt is like so: 我的尝试是这样的:

#include <boost/hana.hpp>
#include <boost/hana/experimental/printable.hpp>

#include <iostream>

namespace hana = boost::hana;

struct foo {};

const auto result{hana::filter(hana::tuple_t<int, foo>, [](auto type) {
  const auto has_plus{hana::is_valid([](auto t)
    -> decltype((void) hana::traits::declval(t) + hana::traits::declval(t)) {})};

  return has_plus(type);
})};

int main()
{
  std::cout << hana::experimental::print(result) << std::endl;
}

This outputs '()', ie. 这输出'()',即。 no types matched where I would expect that the tuple result should contain type<int> . 没有任何类型与我期望的元组result应包含type<int>匹配。

I am using the Boost.Hana version that is packaged with Boost 1.62. 我正在使用Boost 1.62打包的Boost.Hana版本。

Your problem is with operator precedence. 您的问题在于运算符的优先级。

(void)hana::traits::declval(t) + hana::traits::declval(t)

is the same as 是相同的

((void)hana::traits::declval(t)) + hana::traits::declval(t)

The following yields the result you expected: 以下将产生您期望的结果:

(void)(hana::traits::declval(t) + hana::traits::declval(t))

demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM