【发布时间】:2017-12-23 00:25:17
【问题描述】:
前戏
嗨, 也许这个问题是重复的,但我对模板编程比较陌生,实际上我找不到 simple 和 short solution (-> 只能找到兆字节的“ roxxor-template-magic" 我不明白) 匹配我的具体和简单的问题,所以我现在感觉有点失落。
预告
我想使用“type_container”作为类的模板参数。容器是一个简单的结构,它还应该包含一些模板参数包的类型定义。
问题:(与底部的例子有关)
如何定义容器结构中的类型列表并为其设置别名,如何访问它们并将它们转发到工厂类中所需的实体? (没有提升,只有 C++11/14/17)
示例:(会编译,如果我知道解决方案)
#include <map>
#include <vector>
#include <string>
#include <stack>
struct MY_TYPE_CONTAINER
{
using TYPE_MAP = std::map<int, int>;
using TYPE_VECTOR = std::vector<double>;
using PARAMETER_PACK1 = //? -> ...T -> int, std::stack<int>, int
using PARAMETER_PACK2 = //? -> ...T -> double, int, std::string
};
template <typename TYPES>
struct Factory
{
typename TYPES::TYPE_MAP m_map;
typename TYPES::TYPE_VECTOR m_vector;
typename std::tuple<TYPES::PARAMETER_PACK1...> m_tuple;
typename std::tuple<std::shared_ptr<TYPES::PARAMETER_PACK1>...> m_tuple2;
void handlePack2(TYPES::PARAMETER_PACK2... args) { }
};
int main()
{
Factory<MY_TYPE_CONTAINER> oStaticFactory;
oStaticFactory.handlePack2(2.0, 1, "hi");
return 0;
}
当前(最佳?)详细的解决方案(可编译)(基于 John Zwinck 的回答)
#include <map>
#include <vector>
#include <string>
#include <stack>
#include <memory>
struct MY_TYPE_CONTAINER
{
using TYPE_MAP = std::map<int, int>;
using TYPE_VECTOR = std::vector<double>;
using PARAMETER_PACK1 = std::tuple<int, std::stack<int>, int>;
using PARAMETER_SHARED_PTR_PACK_1 = std::tuple<std::shared_ptr<int>, std::shared_ptr<std::stack<int>>, std::shared_ptr<int>>;
using PARAMETER_PACK2 = std::tuple<double, int, std::string>;
};
template <typename TYPES>
class Factory
{
typename TYPES::TYPE_MAP m_map;
typename TYPES::TYPE_VECTOR m_vector;
typename TYPES::PARAMETER_PACK1 m_tuple;
typename TYPES::PARAMETER_SHARED_PTR_PACK_1 m_tuple2;
void handlePack2Impl(typename TYPES::PARAMETER_PACK2 tup) {};
public:
template <typename... Args>
void handlePack2(Args... args) { handlePack2Impl(std::make_tuple(args...)); }
};
int main()
{
Factory<MY_TYPE_CONTAINER> oStaticFactory;
oStaticFactory.handlePack2(2.0, 1, "hi");
return 0;
}
【问题讨论】:
-
C++17、14 还是 11?
-
已将其添加到我的问题中。
-
处理该类型包以声明数据成员相当容易,但you'll be grinding your teeth on the member functions...
标签: c++ templates parameter-passing variadic-templates type-alias