c++ - boost::hana::map 作为数据成员

标签 c++ templates boost template-meta-programming boost-hana

我正在学习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;

现场演示

Live On Coliru

#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/

相关文章:

c++ - 反向代理的典型架构是什么?

c++ - 我应该如何处理 libpq for postgresql 中的错误

C++:模板类二元运算符重载 - 段错误?

c++ - boost::container::vector 和 std::vector 有什么区别

c++ - 如何让 C++ Boost 线程休眠

c++ - 链接器生成的 .map 文件有什么用?

c++ - SFINAE 和模板函数实例化 : Why a template argument cannot be deduced when used in function arguments with a SFINAE-enabled type?

php - CSS 样式表不更新 PHP 模板的任何更改

html - Visual Studio 2010 是否支持 HTML 5?

c++ - boost::sandbox::odeint 安装