为什么不能使用 auto 作为模板类型参数(例如 std::array)?
问题描述:
为什么不允许这样做,例如:
Why is this not allowed, for example:
std::array<auto, 5> myArray {
};
这会让我的生活变得更轻松,因为我可以在数组中存储多种数据类型.我确定有一个合乎逻辑的解释,只是想知道它是什么.
It would make my life so much easier, as I would be allowed to store multiple data-types inside the array. I'm sure there's a logical explanation, just wondered what it was.
答
auto
用于从表达式中推导出一种类型.使用您建议的语法无济于事,因为只能在容器中存储一种类型.如果您需要一种在容器中存储任何类型的方法,请查看boost::any
,以便您可以使用
auto
is used to deduce one type from an expression. Using your suggested syntax would not help because exactly one type can be stored in a container. If you need a way to store any type in the container, take a look at boost::any
, so you can use
std::array<boost::any, 5> myArray;