有没有办法得到value_type来自 std::map<K,V>
类型的变量
例如:
class Foo{
private:
std::map<int,double> myMap;
public:
void Bar(const std::map<int,double>& m)
{
using PairType = m::value_type; //How to enable something like this?
std::vector<PairType> vec(m.size());
read_ints_and_doubles(&vec, m.size()); //expects a void* (legacy lib I'm using)
}
};
显然我知道我可以使用 std::map<int,double>::value_type
,但我希望它对 future 的更改开放。
我考虑过使用 using MyMapType = std::map<int,double>
然后简单地使用 MyMapType
无处不在,但我不想这样做,在我看来,有一种方法可以从变量本身获取此信息,因为这都是静态信息,我不明白为什么我无法访问此信息.
编辑: 这个问题与建议的 dup 大不相同:Declare variables that depend on unknown type in template functions因为我不尝试声明任何变量,而且类型是已知的。
最佳答案
您可以使用 decltype
( wandbox example ):
using PairType = decltype(m)::value_type;
在上面的代码片段中,decltype(m)
计算出 m
的类型。
在您的特定情况下,您可能希望使用 std::remove_reference_t
从评估类型中删除引用 - decltype
不会自动“衰减”评估类型。
C++14 示例:
using PairType = decltype(m)::value_type; std::vector<std::remove_reference_t<PairType>> vec(m.size());
C++11 示例(on wandbox):
using PairType = decltype(m)::value_type; using RemoveRefPairType = typename std::remove_reference<PairType>::type; std::vector<RemoveRefPairType> vec(m.size());
关于C++11 从变量中获取 std::map value_type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39953659/