戏剧前
你好,
也许这个问题是重复的,但我对模板编程相对较新,实际上我找不到simple and 简短的解决方案(-> 只找到兆字节的“roxxor-模板-magic“我不明白)与我具体而简单的问题相匹配,所以我现在感觉有点迷失。
预先信息
我想使用“type_container”作为类的模板参数。容器是一个简单的结构体,它还应该包含一些模板参数包的 typedef.
问题:(与底部的示例相关)
如何在容器结构中定义和别名类型列表,以及如何访问它们并将它们转发到工厂类中所需的实体?
(没有 boost,只有 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;
}
当前(最好的?)详细解决方案(可编译)(基于约翰·兹温克的回答)
#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;
}