在C++ 14中,关联容器似乎已从C++ 11改变 - [associative.reqmts]/13说:
成员函数模板
find,count,lower_bound,upper_bound,并且equal_range不得,除非类型参与重载决议Compare::is_transparent存在.
使比较器"透明"的目的是什么?
C++ 14还提供了这样的库模板:
template <class T = void> struct less {
constexpr bool operator()(const T& x, const T& y) const;
typedef T first_argument_type;
typedef T second_argument_type;
typedef bool result_type;
};
template <> struct less<void> {
template <class T, class U> auto operator()(T&& t, U&& u) const
-> decltype(std::forward<T>(t) < std::forward<U>(u));
typedef *unspecified* is_transparent;
};
Run Code Online (Sandbox Code Playgroud)
因此,例如,std::set<T, std::less<T>>将不会有一个透明的比较,而是std::set<T, std::less<>> …
我想存储一堆键值对象,但值对象本身(及其对它的引用)知道它的键.我还想在只给出密钥的情况下有效地查找这些对象.
class SomeObject
{
private:
//String or integer. int seem cheap enough to duplicate with std::map, but
//strings seem pretty expensive when there may be thousands of objects in existence.
//Reference/Pointer to key is fine
const SomeOtherObject key;
...other stuff...
public:
...methods, some of which use the key in some way...
};
Run Code Online (Sandbox Code Playgroud)
我正在研究一个名为group_bySQL同名模型的递归映射类.
例如,GB是一个group_by将存储指向对象foo分组通过std::string,int以及char密钥类型,在这个顺序.
group_by<foo,std::string,int,char> gb;
Run Code Online (Sandbox Code Playgroud)
group_by提供了一种at( I const& key )存取方法,可用于查看当前的水平图.链接at()调用以检索更深层的地图工作正常.
auto& v = gb.at( k1 ).at( k2 ).at( k3 ).get_vec();
Run Code Online (Sandbox Code Playgroud)
问题
我想创建一个at()被调用的替代方法,at_variadic( Args const& ...args )它可以在一次调用中检索更深层的地图,而无需链接.
auto& w = gb.at_variadic( k1, k2 );
auto& x = gb.at_variadic( k1, k2, k3 );
Run Code Online (Sandbox Code Playgroud)
但是,我遇到了一些问题.首先,我不知道如何指定返回类型,因为它取决于可变参数.也许用decltype(),不知何故?
工作答案
Ecatmur在下面的回答概述了一个很好的方法.
我不得不玩终端案例group_by<>以使编译器满意,但下面的代码,很大程度上基于Ecatmur的答案,似乎与gcc 4.7.2一起正常工作.
#include <cassert>
#include <map>
#include <vector>
#include <iostream>
template< …Run Code Online (Sandbox Code Playgroud)