函数参数数量等于模板整数

Number of function arguments equal to template integer

本文关键字:于模板 整数 参数 数数 函数      更新时间:2023-10-16

说我有一个带有整数模板参数的类。我将如何添加一个给定类型的N参数的函数?如果可能的话,我想避免使用enable_if等。

我目前要做的是:

template<unsigned int N>
class Foo
{
    template <typename To, typename>
    using to = To;
public:
    template<typename... Args>
    void Bar(to<char, Args>... args) // Some arguments of type char
    { /* do stuff */ }
};

这允许调用栏:

Foo<3> myfoo;
myfoo.Bar<int, int, int>('a', 'b', 'c');

但是,我看到两个缺点。首先,参数的数量不一定仅限于N,除非Bar中的代码。

第二,用户需要将模板参数添加到该函数。它们的值实际上不使用,仅使用参数数。这似乎是不必要的,因为我们已经拥有了这个,即N

该功能的最佳用途看起来像这样:

Foo<3> myfoo;
myfoo.Bar('a', 'b', 'c'); // valid

以下调用会生成编译错误。function does not take this many arguments或一些类似的标准编译错误,您会遇到的,好像您将手动定义void(char, char, char)

myfoo.Bar('a', 'b');
myfoo.Bar('a', 'b', 'c', 'd'); // error
myfoo.Bar('a', 'b', "flob"); // error
// ...

如果您使用的是C 14,则可以这样做:

#include <utility>
template<std::size_t N, class = std::make_index_sequence<N>>
class Foo;
template<std::size_t N, std::size_t... Is>
class Foo<N, std::index_sequence<Is...>>{
    void Bar(decltype(Is, char{})... args) // Some arguments of type char
    { /* do stuff */ }
};

[live demo]

对于C 11,您需要实现integer_sequence才能使其正常工作...可以像这样完成