我正在尝试使用 Boost 的 hana::transform
更改 hana::tuple
中的类型.例如,假设我有
constexpr auto some_tuple = hana::tuple_t<int, char *, bool>;
我想生产
constexpr auto transformed_tuple = hana::tuple_t<std::vector<int>,
std::vector<char *>,
std::vector<bool>>;
尝试 1
解决方案对我来说似乎很简单:使用 hana::transform
并使应用函数返回 hana::type_c<std::vector<decltype(T)::type>>
.但是,我无法完成这项工作:
constexpr auto transformed_tuple = hana::transform(some_tuple, [](auto T) {
using inner_type = typename decltype(T)::type;
return hana::type_c<std::vector<inner_type>>;
});
问题是 lambda 表达式不是 constexpr
- 我想留在 C++14 中,即 lambda 不能是 constexpr
.
尝试 2
我的下一个想法:如果我包装 hana::transform
会怎么样?进入decltype
, 然后使用 hana::type_c
在那?这样,lambda 永远不需要求值(只需要推导它的返回类型),并且 constexpr
ness 应该无关紧要:
constexpr auto transformed_tuple =
hana::type_c<decltype(hana::transform(some_tuple, [](auto T) {
using inner_type = typename decltype(T)::type;
return hana::type_c<std::vector<inner_type>>;
}))>;
但是,现在我遇到了 lambda 表达式可能不会出现在“未计算的上下文”中的问题。
我的方法是完全错误的吗?我应该使用 hana::transform
以外的东西吗? ?
感谢您的帮助。
编辑:
示例代码:
#include <boost/hana.hpp>
#include <boost/hana/tuple.hpp>
#include <boost/hana/type.hpp>
namespace hana = boost::hana;
#include <vector>
constexpr auto some_tuple = hana::tuple_t<int, char *, bool>;
/** What I want:
*
* constexpr auto transformed_tuple
* = hana::tuple_t<std::vector<int>,
* std::vector<char *>,
* std::vector<bool>>;
**/
#if ATTEMPT1
constexpr auto transformed_tuple = hana::transform(some_tuple, [](auto T) {
using inner_type = typename decltype(T)::type;
return hana::type_c<std::vector<inner_type>>;
});
#elif ATTEMPT2
constexpr auto transformed_tuple = hana::type_c<decltype(hana::transform(some_tuple, [](auto T) {
using inner_type = typename decltype(T)::type;
return hana::type_c<std::vector<inner_type>>;
}))>;
#endif
最佳答案
Boost.Hana 有 hana::template_
用于将类型应用于返回类型的模板。
#include <boost/hana/assert.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/transform.hpp>
#include <boost/hana/tuple.hpp>
#include <boost/hana/type.hpp>
#include <vector>
namespace hana = boost::hana;
int main() {
constexpr auto some_tuple = hana::tuple_t<int, char *, bool>;
constexpr auto expected_tuple = hana::tuple_t<std::vector<int>,
std::vector<char*>,
std::vector<bool>>;
constexpr auto transformed_tuple = hana::transform(some_tuple, hana::template_<std::vector>);
BOOST_HANA_CONSTANT_CHECK(transformed_tuple == expected_tuple);
}
关于c++ - 在 C++14 中使用 hana::transform 转换元组内部的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49777628/