C ++ 11参数包过载 [英] C++11 parameters pack overload

查看:240
本文介绍了C ++ 11参数包过载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数:

template <typename A>
Foo createFoo() {

    std::initializer_list<std::size_t> list = { Object<A>::getIndex() } );
    return Foo(list);
}

调用方式如下:

Foo foo = createFoo<Bar>();

它正确,返回一个类 Foo

如果有多个参数参数,可以写一个专门的函数吗?

Is it possible to write a specialized function in case there're more than one parameter argument, something like this?

template <typename A1, typename A2, typename...Ax>
Foo createFoo() {

    std::initializer_list<std::size_t> list = { Object<A1>::getIndex(), Object<A2>::getIndex()... } );
    return Foo(list);
}

这样我就可以这样调用:

So that I invoke it this way:

Foo foo = createFoo<Bar, Fred, Wilma>();

它给我一个错误:


错误:扩展模式Object :: getIndex()不包含参数包

error: expansion pattern ‘Object::getIndex()’ contains no argument packs

...部分代码。

我不想有一个函数声明为

I don't want to have a single function declared as

template <typename ...A>
Foo createFoo() {

    std::initializer_list<std::size_t> list = { Object<A>::getIndex() } );
    return Foo(list);
}

因为,假设 Foo class具有优化的逻辑,以便在initializer_list中只有一个 std :: size_t 项,并且我想在我的API中使用它。

because, let's suppose the Foo class has optimized logics in case there's only one std::size_t item in the initializer_list and I want to utilize that in my API.

我使用GCC版本4.8.4与 -std = c ++ 11 选项

I use GCC version 4.8.4 with -std=c++11 option

谢谢。

推荐答案

std::initializer_list<std::size_t> list = { Object<A1>::getIndex(), Object<A2>::getIndex()... } );



<函数调用,它会在其中寻找要扩展的参数包,但 A2 不是参数包, Ax

为什么还要有A1和A2?

Why even have the A1 and A2?

template <typename...Ax>
Foo createFoo() {

然后你可以说 Object< ; Ax> :: getIndex()...

或者如果必须强制执行一定数量的参数,

Or if you must enforce a certain number of parameters, then:

std::initializer_list<std::size_t> list = { Object<A1>::getIndex(),Object<A2>::getIndex(), Object<Ax>::getIndex()... } );

... 参数包,因此这将适用于2种或更多类型。

The ... expansion accepts an empty parameter pack, so this will work for 2 or more types.

这篇关于C ++ 11参数包过载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆