4

I would like to know what is the correct way to retrieve the value of a variadic template constant argument at position N (N is known at compile time). For instance, let's say you have a template that receives a variadic number of function pointers as arguments, and you need to retrieve the second function pointer. For now, all I've been able to come up with is this...

typedef int (*func)(int);

template< func... F >
struct testme
{
 inline int getme(int p) const
 {
  return std::array< func , sizeof... (F) >{F...}[1](p);
 }
};

... which, needless to say, is very hackish. Is there a better way to do this? Thanks.

EDIT:

Based on typedeftemplate's code, I made a version that can accept any type as the variadic template argument. It has been tested to work on an experimental build of GCC 4.6. I figured out it could be useful to somebody else so there it is...

template< std::size_t I, typename T, T... Args >
struct va_lookup;

template< std::size_t I, typename T, T Arg, T... Args >
struct va_lookup< I, T, Arg, Args... >
{
    static_assert(I <= sizeof... (Args), "index is out of bound");
    static constexpr T value = va_lookup< I - 1, T, Args... >::value;
};

template< typename T, T Arg, T... Args >
struct va_lookup< 0, T, Arg, Args... >
{
    static constexpr T value = Arg;
};
4

2 回答 2

4

我认为你可以使用这些方面的东西:

template <int Index, int... Args> struct LookupAtIndex;
template <int Index, int First, int... Rest> struct LookupAtIndex<Index, First, Rest...> {
    static constexpr int result = LookupAtIndex<Index - 1, Rest...>::result;
};
template <int First, int... Rest> struct LookupAtIndex<0, First, Rest...> {
    static constexpr int result = First;
};

我还没有对此进行测试,但至少从直觉上看,它似乎应该可以正常工作。

于 2011-01-24T22:37:46.820 回答
1

这是您的解决方案的一个变体,可能更可口:

typedef int (*func)(int);

template< func... F >
struct testme
{
    static const std::array< func , sizeof... (F) > ptrs_;

    int getme(int p) const
    {
        return ptrs_[1](p);
    }
};

template< func... F >
const std::array< func , sizeof... (F) >
testme<F...>::ptrs_ = {F...};

您的用例的基本问题之一是函数指针不像整数类型那样容易进行模板元编程。

于 2011-01-25T03:05:44.607 回答