繁体   English   中英

根据作为参数接收的函数,定义具有模板化键类型的std :: map

[英]Define a std::map with a templated Key type based on a function that is received as a parameter

我的目标是拥有一个返回映射的函数,该映射的Key类型会根据作为参数传递给我的函数的函数而改变。

到目前为止,我具有以下模板化函数(C ++ 11)作为唯一可编译的解决方案:

    template <typename Container, typename Function, typename KeyType>
    std::map< KeyType, std::vector<typename Container::value_type> > 
    group_by(Container &container, Function function, KeyType keyHint) { ...

现在,这允许我以这种方式使用该函数:

// the last parameter is just a type hint for the compiler
std::map<int, std::vector<int>> m = group_by(vec, func_that_returns_an_int, 1337);
...
std::map<int, std::vector<int>> m = group_by(vec, func_that_returns_an_int, -1);

// if we pass a function that returns bool, the map's key will be boolean
// the last parameter passed is just a hint for the compiler
std::map<bool, std::vector<int>> m = group_by(vec, is_even, true);
...
std::map<bool, std::vector<int>> m = group_by(vec, is_even, false);

我的目标是不必传递随机值来提示编译器Map的Key类型应该是什么,我希望我可以这样做:

std::map<int, std::vector<int>> m = group_by<int>(vec, func_that_returns_an_int);
...
std::map<bool, std::vector<int>> m = group_by<bool>(vec, is_even);

还是有可能吗?

std::map<bool, std::vector<int>> m = group_by(vec, is_even);

我正在使用auto和decltype进行操作,以查看编译器是否可以由操作的左侧提示而没有运气。

auto group_by(Container &container, Function function) -> std::map< decltype(function(Container::value_type)), >

更改顺序或模板参数将允许您调用它

group_by<int>(vec, func_that_returns_an_int);

所以改变

template <typename Container, typename Function, typename KeyType>
std::map< KeyType, std::vector<typename Container::value_type> > 
group_by(Container &container, Function function, KeyType keyHint)

template <typename KeyType, typename Container, typename Function>
std::map< KeyType, std::vector<typename Container::value_type> > 
group_by(Container &container, Function function)

要完全删除KeyType ,必须从其他参数推导出它:

template <typename Container, typename Function>
auto group_by(Container &container, Function function)
-> std::map<decltype(function(*container.begin())),
            std::vector<typename Container::value_type> > 

您可以使用std::result_of<>

#include <map>
#include <vector>
#include <type_traits>

template <typename Container, typename Function, typename KeyType = std::result_of_t<Function()>>
auto group_by(Container c, Function f) -> std::map< KeyType, std::vector<typename Container::value_type>>
{
    return // ...
}

int bar() { return 42; }

int main()
{
    auto v = group_by(std::vector<double>{}, bar);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM