我正在学习boost::hana
用于个人项目。
在下面的代码片段中,我创建了一个 boost::hana::map
有一个type_c<T>
作为键和 Foo<T>
的实例作为值。
它有效,但我真的很想使用 my_map
变量作为类成员并且不能使用auto
成员声明中的限定符。而且如果我能有机会通过types
那就太好了元组以某种方式(作为模板参数或作为构造函数参数)。
你有什么建议吗?
#include <iostream>
#include "boost/hana.hpp"
#include <typeinfo>
using namespace boost;
template<typename T>
class Foo {
T t;
public:
void print() { std::cout <<typeid(T).name() << t; }
};
int main() {
auto types = hana::tuple_t<float, int, std::string>;
auto my_map = boost::hana::unpack(types, [](auto ...t) {
return boost::hana::make_map(boost::hana::make_pair(t, Foo<typename decltype(t)::type>()) ...);
});
my_map[hana::type_c<int>].print();
}
最佳答案
问题是 lambda 不能在未计算的上下文中使用 (decltype
)。
当然,从 c++14 开始,我们可以在任何自由函数上使用推导的返回类型:
namespace detail {
template <typename... T>
static inline auto make_foo_map() {
return boost::hana::unpack(hana::tuple_t<T...>, [](auto... t) {
return boost::hana::make_map(boost::hana::make_pair(t, Foo<typename decltype(t)::type>())...);
});
}
}
template <typename... T>
using FooMap = decltype(detail::make_foo_map<T...>());
现在很简单:
FooMap<float, int, std::string> my_map;
现场演示
#include "boost/hana.hpp"
#include <iostream>
#include <typeinfo>
using namespace boost;
template <typename T> class Foo {
T t;
public:
void print() { std::cout << typeid(T).name() << "t\n"; }
};
namespace detail {
template <typename... T>
static inline auto make_foo_map() {
return boost::hana::unpack(hana::tuple_t<T...>, [](auto... t) {
return boost::hana::make_map(boost::hana::make_pair(t, Foo<typename decltype(t)::type>())...);
});
}
}
template <typename... T>
using FooMap = decltype(detail::make_foo_map<T...>());
int main() {
FooMap<float, int, std::string> my_map;
my_map[hana::type_c<int>].print();
my_map[hana::type_c<float>].print();
my_map[hana::type_c<std::string>].print();
}
关于c++ - boost::hana::map 作为数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48327016/