cuốn sách gpt4 ai đã làm

c++ - hàm mẫu biến thiên: số đối số cho mỗi đối số

In lại Tác giả: Walker 123 更新时间:2023-11-28 02:46:23 27 4
mua khóa gpt4 Nike

我正在尝试使用 C++11 中的可变参数函数模板,并通过如下代码了解了基本思想:

void helper()
{
std::cout << "No args" << std::endl;
}

template< typename T >
void helper( T&& arg )
{
size_t n = 0;
std::cout << "arg " << n << " = " << arg << std::endl;
helper();
}

template< typename T, typename... Arguments >
void helper( T&& arg, Arguments&& ... args )
{
size_t n = sizeof...( args );
std::cout << "arg " << n << " = " << arg << std::endl;
helper( args... );
}

但是,我想要的是参数编号(代码中的变量 n)向上计数而不是向下计数。我怎样才能优雅地做到这一点?我可以编写一个包装函数来创建“隐藏”参数计数,但我觉得应该有更简洁的方法吗?

Cảm ơn!

câu trả lời hay nhất

你的意思是这样的吗?我nghĩ我明白你在找什么,但如果不是,我会毫不犹豫地放弃这个答案:

#include 
#include

void helper()
{
std::cout << "no args" << std::endl;
}

template
void helper(T&& arg)
{
std::cout << "arg " << N << " = " << arg << std::endl;
}

template
void helper(T&& arg, Args&&... args)
{
helper(std::forward(arg));
helper(std::forward(args)...);
}

template
void helper(T&& arg, Args&& ... args)
{
helper<0>(std::forward(arg), std::forward(args)... );
}

int chính()
{
helper();
std::cout << '\n';

helper("single");
std::cout << '\n';

helper("one", 2U);
std::cout << '\n';

helper(1,"two", 3.0, 4L);
std::cout << '\n';

trả về 0;
}

đầu ra

no args

arg 0 = single

arg 0 = one
arg 1 = 2

arg 0 = 1
arg 1 = two
arg 2 = 3
arg 3 = 4

See it live

关于c++ - 可变模板函数 : argument number for each argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24268051/

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress