函数参数数量等于模板整数
Number of function arguments equal to template integer
说我有一个带有整数模板参数的类。我将如何添加一个给定类型的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
才能使其正常工作...可以像这样完成
相关文章:
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 为什么初始化 std::vector 时不能使用模板整数?
- 类成员函数参数列表是否可以依赖于模板参数?
- 依赖于模板的错误
- 将 c++ 类成员函数专用于模板类
- C++ 使函数调用依赖于模板参数
- c ++如何将模板应用于模板类的孩子/朋友?
- 如何修复"没有依赖于模板参数的参数'glGenVertexArrays'......"C++ 中的错误
- 反转模板(整数)参数的顺序
- 如何转发声明依赖于变量定义的类,而变体定义又依赖于模板化类?
- 动态强制转换适用于模板成员函数内的共享指针和弱指针,无需代码重复
- 如何确保 "<<" 运算符适用于模板化 ADT 定义中的任何泛型类型?
- 将 const 限定符应用于模板参数时的不同编译器行为
- 如何定义依赖于模板参数的类型定义
- 如何使用类型专用化模板方法,该类型本身就是一个模板,其中只有返回类型依赖于模板类型
- 如何扩展类模板整数列表
- PHP 相当于C++模板
- 仅专用于模板类的一个方法(部分)
- 函数参数数量等于模板整数
- 依赖于模板的实现