我的情况:
我经常需要一个结构向量,其中一个字段可以被认为是一个键或 ID,而不是将它昂贵地存储在地图中(内存使用在这个应用程序中非常重要)我想将它存储在一个平面向量中但提供了一个类似地图的界面,用于按键查找元素。
我对这个问题的第一个解决方案:
template <class T, class Key, class KeyFn>
class TKeyedVector : public std::vector<T>
{
public:
const_iterator find(const Key& key) const {return std::find_if(begin(), end(), [&](const T& entry) {return keyFn(entry)==key; }); }
KeyFn keyFn;
};
struct KeyedDataEntry
{
std::string key;
int value;
struct KeyExtractor {
const std::string& operator()(const KeyedDataEntry& e) const {return e.key; };
};
};
using KeyedDataArray = TKeyedVector<KeyedDataEntry, std::string, KeyedDataEntry::KeyExtractor>;
现在这一切都有效,但我希望能够KeyExtractor
通过使用指向嵌入类型的成员变量的指针来消除对类型的需求:
template <class T, class Key, Key T::* keyFn>
class TKeyedVector : public std::vector<T>
{
public:
const_iterator find(const Key& key) const {return std::find_if(begin(), end(), [&](const T& entry) {return keyFn(entry)==key; }); }
};
using KeyedDataArray = TKeyedVector<KeyedDataEntry, std::string, &KeyedDataEntry::key>;
但是我无法让它工作。我一直在寻找std::mem_fn
线索的实现,但我不知道该怎么做。我得到的错误是这样的:
warning C4353: nonstandard extension used: constant 0 as function expression. Use '__noop' function intrinsic instead
有什么线索吗?
编辑: http: //ideone.com/Qu6TEy上的示例版本