What is the appropriate way to get the value of the constant argument of a C ++ variator constant in position N?

I would like to know what is the correct way to get the value of the argument argument of the variational pattern at position N (N is known at compile time). For example, suppose you have a template that receives a variable number of function pointers as arguments, and you need to get a second function pointer. So far, all I could come up with is ...

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, of course, is very hacker. Is there a better way to do this? Thanks.

EDIT:

Based on the typedeftemplate code, I made a version that can accept any type as an argument to the variational template. It has been tested to work on the experimental build of GCC 4.6. I realized that this might be useful to someone else, so this ...

 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
source share
2 answers

You can use something in this direction, I think:

 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; }; 

I have not tested this, but at least it seems intuitively that it should work correctly.

+4
source

Here is a variant of your solution that may be more enjoyable:

 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...}; 

One of the main problems in your use case is that function pointers are not so easy to meta-program templates with integral types.

+1
source

Source: https://habr.com/ru/post/1336876/


All Articles