gpt4 book ai didi

C++ 函数 : Variadic templates with no arguments

转载 作者:太空狗 更新时间:2023-10-29 20:29:05 27 4
gpt4 key购买 nike

我不确定这个问题是否已经得到解答。但它是这样的:

我想知道是否可以做类似的事情

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

关于C++ 函数 : Variadic templates with no arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11184223/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com