C++函数:没有参数的可变参数模板
C++ function : Variadic templates with no arguments
我不确定这个问题是否已经得到回答。但事情是这样的:
我想知道是否有可能做类似的事情
template<typename...classes>
void createObject(){
//pass each type into my template function wich takes one type only.
}
我真的不明白它是如何工作的。我无法提供任何函数参数的原因是因为我应该在方法中调用的模板函数只采用一种类型。这是因为它根据对象的类型返回一个对象。
有什么建议吗?
注意:海湾合作委员会 4.6.2
template<typename...>
struct caller;
template<typename T, typename...Rest>
struct caller<T, Rest...>
{
static void call()
{
create<T>();
caller<Rest...>::call();
}
};
template<>
struct caller<>
{
static void call()
{
}
};
//since you've not mentioned the return type, I'm assuming it to be void
//if it is not void, then I don't know what you're going to return, and HOW!
template<typename...classes>
void createObject(){
caller<classes...>::call();
}
演示 : http://ideone.com/UHY8n
备选方案(较短的版本):
template<typename...>
struct typelist{};
template<typename T, typename ... Rest>
void call(typelist<T,Rest...>)
{
create<T>();
call(typelist<Rest...>());
};
void call(typelist<>) { }
template<typename...classes>
void createObject(){
call(typelist<classes...>());
}
演示 : http://ideone.com/cuhBh
一种方法是使用以下函数来扩展调用:
template <typename... Ts>
void swallow(Ts&&...) {
}
我假设您要调用以下函数:
template <typename T>
void create() {
}
在这种情况下,你需要一个帮助函数,将 void create
转换为返回某些内容的函数,以便我们可以在 swallow
的 arg-list 中扩展它(如果你的 create
函数已经是非 void,那么这个额外的步骤是不必要的):
template <typename T>
int createHelper() {
create<T>();
return 0;
}
template<typename... Ts>
void createObject(){
swallow(createHelper<Ts>()...);
}
编辑:代替createHelper,我们可以用逗号运算符使用一个技巧:
swallow((create(), 0)...);
相关文章:
- 在不传递参数数量且只有3个点的情况下,如何使用变差函数
- 如何使用可变参数模板强制转换每个变体类型
- 关于如何在具有单个参数的变体构造中选择替代方案?
- 调用参数排列不变函数 f(i++, i++)
- 参数归纳与标准::变体
- 模板化回调参数的逆变,如 C# 中的逆变
- 如何在没有参数包的情况下编写变差函数
- 通过具有嵌套类的工厂类获取多个变异类模板参数包
- 获取模板参数的成员变量值列表
- 保留短 lambda 用作函数的中间参数,使用 clang 格式保持不变
- 如何定义变体<x,y,z>提取模板参数的子类型
- 正确对齐内存模板,参数顺序不变
- 递归中不同参数类型的变元模板函数
- 通过函数指针传递给变差函数的参数会更改其值
- 提升预定义为带有参数的全局 lambda 的变体访问者
- 使用可变参数模板参数提升变体访问者
- boost ::变体 - 为什么模板参数比const字符串参数具有更高的优先级
- 将变参数包中的值加载到临时数组中
- 使用额外参数提升变体访客
- 正在将动态数组元素解析为参数?(变音符)