2015-10-16 43 views
2
#include <string> 
#include <utility> 
#include <vector> 
#include <boost/hana.hpp> 
namespace hana = boost::hana; 

template <typename ...T> 
void indexed_T_work(T&& ...args) 
{ 
    auto indices = hana::range_c<std::size_t, 0, sizeof...(T)>; 
    auto types = hana::make_tuple(std::forward<T>(args)...); 
    hana::for_each(
     hana::zip(indices, types) 
     , [](auto&& pair_) { /* Do index-dependent work with each `T` */ } 
     ); 
} 

int main() 
{ 
    indexed_T_work(5, 13, std::vector<std::string>{}, 32.f, 42, "foo"); 
} 

我想在hana::tuplehana::range_c,但hana::range_c使用hana::zip不被認爲是序列,這是hana::zip的要求。這個決定背後的推理是什麼?我如何(習慣性地)在尊重這個決定的同時實現我的目標?爲什麼`boost :: hana :: range_c`不是序列?

回答

5

首先,有幾種解決方案:

溶液1

auto indices = hana::to<hana::tuple_tag>(hana::range_c<std::size_t, 0, sizeof...(T)>); 
auto types = hana::make_tuple(std::forward<T>(args)...); 
hana::for_each(hana::zip(indices, types), hana::fuse([](auto i, auto&& x) { 
    // ... 
})); 

溶液2

auto indices = hana::range_c<std::size_t, 0, sizeof...(T)>; 
auto types = hana::make_tuple(std::forward<T>(args)...); 
hana::for_each(indices, [&](auto i) { 
    auto& x = types[i]; 
    // ... 
}); 

溶液3

auto types = hana::make_tuple(std::forward<T>(args)...); 
hana::size_c<sizeof...(T)>.times.with_index([&](auto i) { 
    auto& x = types[i]; 
    // ... 
}); 

(1)具有使每個args因爲zip返回序列的序列的拷貝的缺點,和其中所有的花是由值。由於這可能不是您想要的,因此您應該在解決方案(2)(3)之間挑選您喜歡的任何一個,它們確實相當。

現在,爲什麼range s不建模Sequence概念是因爲這沒有意義。 Sequence概念要求我們能夠使用hana::make函數創建任意Sequence。因此,對於任何Sequence標籤S,hana::make<S>(...)都必須創建包含...的標籤SSequence。但是,range必須在某個間隔中包含連續的integral_constant s。因此,如果rangeSequence,則hana::make<hana::range_tag>(...)應該包含任何...,如果...不是連續integral_constant s,則打破的不變量。例如,考慮

hana::make<hana::range_tag>(hana::int_c<8>, hana::int_c<3>, 
          hana::int_c<5>, hana::int_c<10>) 

這應該是一個rangeintegral_constant小號8,3,5,10,這沒有任何意義。顯示爲什麼range不能是Sequence的另一個類似示例是permutations算法。 permutations算法需要Sequence並返回包含所有排列的SequenceSequence。顯然,由於range只能容納integral_constant s,所以嘗試創建rangerange是沒有意義的。像這樣的例子比比皆是。

換句話說,range太專業化,以模擬Sequence概念。擁有這樣一個專業化結構的好處是編譯時效率很高。缺點是它不是通用容器,有些操作無法完成(如zip)。但是,如果您知道折衷是什麼,則可以完全採取range並將其轉換爲完整的序列。

相關問題