我刚刚开始用可变参数版本替换我的一些旧模板,以避免代码重复(或丑陋的宏)用于具有可变数量参数的重载。
我遇到但尚未解决的一个问题是:如何从属于“混合类型名...”的任何类型中删除 const& ?
这是我的例子:
#include <tuple>
// old version to be replaced
namespace old_version
{
template<typename T> struct struct_const_deref { typedef T Type; };
template<typename T> struct struct_const_deref < const T& > { typedef T Type; };
template < typename F, typename T1 >
void exec(F* pObj, void(F::*pFct)(T1))
{
typename struct_const_deref<T1>::Type t1;
// some code that fills t1
(pObj->*pFct)(t1);
}
template < typename F, typename T1 , typename T2 >
void exec(F* pObj, void(F::*pFct)(T1, T2))
{
typename struct_const_deref<T1>::Type t1;
typename struct_const_deref<T2>::Type t2;
// some code that fills t1, t2
(pObj->*pFct)(t1, t2);
}
}
// new variadic version
namespace variadic
{
template< typename... Args > struct struct_const_deref_tuple { typedef std::tuple< Args... > Tuple; };
template< typename... Args > struct struct_const_deref_tuple < const Args&... > { typedef std::tuple< Args... > Tuple; };
template < typename F, typename... Args >
void exec(F* pObj, void(F::*pFct)(Args... args))
{
typename struct_const_deref_tuple< Args... >::Tuple tN;
// some code that fills tN
// some helper template that 'extracts' the tuple and calls (pObj->*pFct)(ExtractedArgs...)
}
}
struct Test
{
void foo(int i) {}
void bar(const float& f, const int& i) {}
void buu(const float& f, int i) {}
};
int main(int argc, char* argv[])
{
Test t;
old_version::exec(&t, &Test::foo); // ok
old_version::exec(&t, &Test::bar); // ok
old_version::exec(&t, &Test::buu); // ok
variadic::exec(&t, &Test::foo); // ok
variadic::exec(&t, &Test::bar); // ok
variadic::exec(&t, &Test::buu); // fails (the struct_const_deref_tuple does not 'catch' my case; 'tN' will be std::tuple<const float&, int>
return 0;
}
由于旧解决方案需要每个参数数量的版本,我想用可变参数解决方案替换它。
不幸的是,可变参数版本失败了
Test::buu
因为 tN 变成
std::tuple<const float&, int>
但显然需要
std::tuple<float, int>
让我工作。
欢迎任何想法:)