7

Assuming I have a member function pointer how I could write code that automatically deduce parameters for given template signature:

 template<typename T> class Foo {};

 template<typename R, typename C, typename... A>
 class Foo<R(C, A...)> { };

For C and R there is no problem as something similar to this does the trick:

template<typename R, typename C, typename... A> 
R deduce_R_type(R(C::*)(A...));

template<typename R, typename C, typename... A>
C deduce_C_type(R(C::*)(A...));

Then I can actually plug it in to the Foo instantiation but how to deduce the types coming from the variadic part of the template?

Foo<
decltype(deduce_R_type(&SomeClass::SomeFunction)) (
decltype(deduce_C_type(&SomeClass::SomeFunction)), ___ ??? ___)> instance
4

1 回答 1

7

你至少需要一个助手和类似的东西std::tuple

template<typename R, typename C, typename... A>
std::tuple<A...> deduce_A_tuple(R(C::*)(A...));

template<typename R, typename C, typename T>
struct FooHelper;

template<typename R, typename C, typename... A>
struct FooHelper< R, C, std::tuple<A...> >
{
    typedef Foo< R( C, A... ) > type;
};

然后你可以使用:

FooHelper< decltype(deduce_R_type(&SomeClass::SomeFunction)),
           decltype(deduce_C_type(&SomeClass::SomeFunction)), 
           decltype(deduce_A_tuple(&SomeClass::SomeFunction)) >::type instance;

活生生的例子


正如用户DyP指出的那样,无论如何都必须使用帮助程序时,它可能会简单得多:

template<typename>
struct FooHelper;

template<typename R, typename C, typename... A>
struct FooHelper< R (C::*)(A...) >
{
    using type = Foo< R( C, A... ) >;
};

并将其用作

FooHelper< decltype(&SomeClass::SomeFunction) >::type instance;
于 2013-10-15T17:41:50.027 回答