kfm*_*e04 7 c++ templates variadic-functions c++11
我正在研究一个名为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< typename T, typename... Args >
struct group_by
{
using child_type = T;
std::vector<T*> m_vec;
void insert( T* t )
{
m_vec.push_back( t );
}
child_type&
at( size_t i )
{
return *m_vec[i];
}
};
template< typename T, typename I, typename... Args >
struct group_by<T,I,Args...>
{
using child_type = group_by<T,Args...>;
std::map<I,child_type> m_map;
void insert( T* t )
{
m_map[ *t ].insert( t );
}
child_type& at( I const& key )
{
return m_map.at( key );
}
template<typename... Ks>
auto
at( I const& i, Ks const&...ks )
-> decltype( m_map.at( i ).at( ks... ) )
{
return m_map.at( i ).at( ks... );
}
};
// -----------------------------------------------------------------------------
struct foo
{
std::string s;
int i;
char c;
operator std::string() const { return s; }
operator int () const { return i; }
operator char () const { return c; }
bool operator==( foo const& rhs ) const
{
return s==rhs.s && i==rhs.i && c==rhs.c;
}
};
int main( int argc, char* argv[] )
{
foo f1{ "f1", 1, 'z' };
foo f2{ "f2", 9, 'y' };
foo f3{ "f3", 3, 'x' };
foo f4{ "f1", 4, 'k' };
group_by<foo,std::string,int,char> gb;
gb.insert( &f1 );
gb.insert( &f2 );
gb.insert( &f3 );
gb.insert( &f4 );
std::string k1{ "f1" };
int k2{ 1 };
char k3{ 'z' };
auto& a = gb.at( k1 ).at( k2 ).at( k3 ).at( 0 );
auto& b = gb.at( k1 ).at( k2 ).m_map;
auto& c = gb.at( k1 ).m_map;
auto& d = gb.at( k1, k2 ).m_map;
auto& e = gb.at( k1, k2, k3 ).m_vec;
auto& f = gb.at( k1, k2, k3, 0 );
assert( a==f1 );
assert( b.size()==1 );
assert( c.size()==2 );
assert( d.size()==1 );
assert( e.size()==1 );
assert( f==f1 );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
链式方法调用本质上是递归的,因此需要at递归地实现:
child_type& at( I const& key ) {
return m_map.at( key );
}
template<typename J, typename... Ks>
auto at(const I &i, const J &j, const Ks &...ks)
-> decltype(m_map.at(i).at(j, ks...)) {
return m_map.at(i).at(j, ks...);
}
Run Code Online (Sandbox Code Playgroud)
请注意,由于at需要至少 1 个参数,因此可变参数形式至少需要 2 个参数。这比在 上调度要容易得多sizeof...,并且应该更容易阅读。
| 归档时间: |
|
| 查看次数: |
371 次 |
| 最近记录: |