C++ 接受相同类型的可变数量的参数

C++ 接受相同类型的可变数量的参数,c++,templates,c++11,variadic-templates,C++,Templates,C++11,Variadic Templates,我正在尝试实现一个函数,该函数可以接受任意数量的std::size\t变量并相应地使用它们 我希望能够按如下方式调用该函数(为了参数起见,我们将其称为Foo): Foo( some_other_type, 1, 2, 5, 7, 10 ); Foo( some_other_type, {1, 2, 5, 7, 10} ); 我尝试了以下方法: template <typename T, std::size_t... Coords> T Foo( T tSomething, Coo

我正在尝试实现一个函数,该函数可以接受任意数量的
std::size\t
变量并相应地使用它们

我希望能够按如下方式调用该函数(为了参数起见,我们将其称为
Foo
):

Foo( some_other_type, 1, 2, 5, 7, 10 );
Foo( some_other_type, {1, 2, 5, 7, 10} );
我尝试了以下方法:

template <typename T, std::size_t... Coords>
T Foo( T tSomething, Coords... coords );
template <typename T, std::size_t... Coords>
T Foo( T tSomething /*, Coords... coords*/ )
{
    Bar<sizeof...(Coords)> bar( /*coords...*/ Coords... );
    // Do stuff...
    return bar.tProperty;
}
这意味着我无法解包参数来构造另一个类型


编辑:我希望有类似于可变模板的东西,以及为什么
std::initializer\u list
Foo
的递归版本不起作用的原因是,假设我有一个类
Bar
,其构造函数需要根据特定实例化的变量数量,我希望做一些类似的事情:

template <typename T, std::size_t... Coords>
T Foo( T tSomething, Coords... coords );
template <typename T, std::size_t... Coords>
T Foo( T tSomething /*, Coords... coords*/ )
{
    Bar<sizeof...(Coords)> bar( /*coords...*/ Coords... );
    // Do stuff...
    return bar.tProperty;
}
模板
T Foo(T tSomething/*,Coords…Coords*/)
{
酒吧酒吧(/*coords…*/coords…);
//做些事情。。。
返回条.t属性;
}

但是我希望能够像上面所说的那样调用
Foo
,而不是使用模板列表。

起初我发现解决这个问题的方法有点违反直觉。您需要一个“typename…Coords”,而不是将其声明为size\u t。这是因为您希望编译器填写类型名

通过强制将其用作尺寸,可以确保类型安全

template <typename T, typename... Coords>
T Foo( T tSomething, const Coords... coords )
{
    std::array<size_t, sizeof...(Coords)>unpacked_coords {coords...};
    for (size_t coord : unpacked_coords)
    {
        // do stuff
    }
    return tSomething;

}

如您所愿:)

@nosid我已更新了我的问题,以解释为什么这不是该问题的重复。@Shaktal那么它是该问题的重复或可能是数十个类似问题中的一个(这表明我们需要更好的语言支持)。请参阅。这是我对一个几乎相同的问题的回答。我的回答解释了如何通过编译时谓词和
static\u assert()
实现统一类型,以获得有用的错误消息。“虽然您可能需要显式地将数字创建为size\t”,但为什么需要这样做?@dyp没有size\t初始化,数字是int,并且可能与size\t的大小不同,怎么了?找到问题了。coords需要常量才能发送ints。???我不认为
Coords
需要
const
才能接受ints。你有没有一个最简单完整的例子来说明这个问题?