【问题标题】:C++: can we collect types?C++:我们可以收集类型吗?
【发布时间】:2012-01-08 13:19:57
【问题描述】:

我想知道我们是否可以做类似的事情

a.pushType<int>
a.pushType<std::string>
a.pushType<char>

我们可以这么称呼

std::map<a.T1, a.T3> mymap;
std::map<a.T1, a.T2> mymap;
someClass<a.T1, a.T2, a.T3>

我需要它不是在运行时,而是在编译时(用于在我的仅标头库中提供它。)

C++03 和 Boost 可以吗?

【问题讨论】:

  • 为什么你不能用T1 & T2 适当的类型来写std::map&lt;T1,T2。类型是编译器的东西。值在运行时存在。

标签: c++ boost types


【解决方案1】:

这是一种称为 TypeLists 的机制;据我所知,它最初是由 Andrei Alexandrescu 在Modern C++ Design中提出的。在 Alexandrescu 的库 Loki 中有一个 TypeLists 的实现。我也认为 Boost.MPL 有一个类似的结构:vector

【讨论】:

  • @myWallJSON:您编辑了问题。之前不清楚。
【解决方案2】:
typedef std::pair<int, std::string> a;

std::map<a::first_type, a::second_type> mymap;

类型必须在编译时知道。有一些方法可以解决它,但它们非常复杂。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 2014-05-17
    • 2019-07-01
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多