检索 C++ 的值的适当方法是什么?位置 N 处的可变参数模板常量参数?
我想知道检索位置 N 处的可变参数模板常量参数的值的正确方法是什么(N 在编译时已知)。例如,假设您有一个模板,该模板接收可变数量的函数指针作为参数,并且您需要检索第二个函数指针。目前,我能想到的就是这个……
typedef int (*func)(int);
template< func... F >
struct testme
{
inline int getme(int p) const
{
return std::array< func , sizeof... (F) >{F...}[1](p);
}
};
不用说,这是非常黑客的。有更好的方法吗?谢谢。
编辑:
基于typedeftemplate的代码,我制作了一个可以接受任何类型作为可变参数模板参数的版本。它已经过测试,可以在 GCC 4.6 的实验版本上运行。我发现它可能对其他人有用,所以就这样......
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;
};
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;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想,你可以按照这些思路使用一些东西:
我还没有对此进行测试,但至少直观上它似乎应该正确工作。
You can use something along these lines, I think:
I haven't tested this out, but at least intuitively it seems like it should work out correctly.
这是您的解决方案的一个变体,可能更容易接受:
您的用例的基本问题之一是函数指针不像整数类型那样容易进行模板元编程。
Here is a variation of your solution that might be more palatable:
One of the basic problems with your use case is that function pointers aren't as easy to do template meta-programming with as integral types.