我正在尝试学习C++11的当前接受特性,但auto和decltype一直让我困扰。作为学习练习,我正在使用一些通用函数扩展std类列表。
template<class _Ty, class _Ax = allocator<_Ty>>
class FList : public std::list<_Ty, _Ax>
{
public:
void iter(const function<void (_Ty)>& f)
{
for_each(begin(), end(), f);
}
auto map(const function<float (_Ty)>& f) -> FList<float>*
{
auto temp = new FList<float>();
for (auto i = begin(); i != end(); i++)
temp->push_back(f(*i));
return temp;
}
};
auto *ints = new FList<int>();
ints->push_back(2);
ints->iter([](int i) { cout << i; });
auto *floats = ints->map([](int i) { return (float)i; });
floats->iter([](float i) { cout << i; });
对于会员地图,我希望返回类型可以根据传递的函数返回值而通用化。因此,对于返回类型,我可以这样做。
auto map(const function<float (_Ty)>& f) -> FList<decltype(f(_Ty))>*
在函数模板中还需要删除float类型。
auto map(const function<auto (_Ty)>& f) -> FList<decltype(f(_Ty))>*
我可以使用模板类,但这会使得实例的使用更加冗长,因为我必须指定返回类型。
template<class T> FList<T>* map(const function<T (_Ty)>& f)
为了回答我的问题,我正在尝试找出如何定义一个不使用模板类但仍具有通用类型返回的映射。