【问题标题】:tuple - get_or helper functiontuple - get_or 辅助函数
【发布时间】:2013-07-09 05:57:33
【问题描述】:

我需要一个元组辅助函数,如果请求的类型在元组中不存在,它会返回一个默认构造的空类型。

例如

std::tuple<bool, int> tuple(true, 0);

static_assert(std::is_same<decltype(get_or<double, std::nullptr_t>(tuple)), 
                           std::nullptr_t>::value, "");
assert(get_or<double, std::nullptr_t>(tuple) == nullptr);

我想我需要一些增强融合魔法,但我还没有完全弄清楚。有什么建议吗?

【问题讨论】:

  • 你的第一行不应该编译。您需要传递第二个构造函数参数。
  • @juanchopanza - 我认为第一行实际上是问题所在。他希望能够像这样初始化元组并将第二个参数设置为默认值
  • @asafrob 好的。提出问题的方式让我感到震惊。没有辅助函数可以修复该编译器错误。
  • 我认为这是同一个问题stackoverflow.com/questions/13301863/…
  • @juanchopanza:你是对的。我已经修正了错字。

标签: c++ tuples template-meta-programming boost-fusion


【解决方案1】:

这里有一个tuple_index 助手,它返回std::tuple 中给定类型的索引。 (可以很容易地调整它以使用诸如is_convertible 之类的谓词。)

template< typename elem, typename tup, std::size_t offset = 0 >
struct tuple_index
    : std::integral_constant< std::size_t, offset > {};

template< typename elem, typename head, typename ... tail, std::size_t offset >
struct tuple_index< elem, std::tuple< head, tail ... >, offset >
    : std::integral_constant< std::size_t, tuple_index< elem, std::tuple< tail ... >, offset + 1 >::value > {};

template< typename elem, typename ... tail, std::size_t offset >
struct tuple_index< elem, std::tuple< elem, tail ... >, offset >
    : std::integral_constant< std::size_t, offset > {};

你可以这样构建它:

template< typename result, typename fallback, typename tuple >
typename std::enable_if< tuple_index< result, typename std::decay< tuple >::type >::value
                         == std::tuple_size< typename std::decay< tuple >::type >::value,
    fallback >::type
get_or( tuple && t ) { return {}; }

template< typename result, typename fallback, typename tuple >
typename std::enable_if< tuple_index< result, typename std::decay< tuple >::type >::value
                         != std::tuple_size< typename std::decay< tuple >::type >::value,
    result >::type
get_or( tuple && t ) {
    return std::get< tuple_index< result, typename std::decay< tuple >::type >::value >
        ( std::forward< tuple >( t ) );
}

http://ideone.com/ZdoWI7

所有decay 都是必需的,因为元函数区分tupletuple &amp;

【讨论】:

  • 太棒了!虽然我希望使用 boost mpl 或 fusion 来获得更简单的辅助函数?
  • 这已经很简单了,只是因为我复制粘贴了decay 而变得冗长。您可以通过中介派送来排除它。我也有点怀疑forward 在做什么;我只是防御性地添加了它。
猜你喜欢
  • 2014-01-23
  • 2021-05-24
  • 1970-01-01
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
相关资源
最近更新 更多