gpt4 book ai didi

c++ - 如何包装可变参数模板函数?

转载 作者:行者123 更新时间:2023-11-28 01:28:21 24 4
gpt4 key购买 nike

比方说,我有类似的东西

#include <iostream>

template <class Arg>
void helper(Arg&& arg) {
// do something with the type and value
}

void vt(){}

template <class Arg, class... Args>
void vt(Arg&& arg, Args&&... rest) {
helper(arg);
vt(rest...);
}

int main() {
vt(1, 1.1, "abc");
}

现在,我的问题是如何在 cpp 文件中包装像 vt() 这样的可变参数模板函数。基本上,我想对我的库中的客户端隐藏实现。

我考虑过使用 va_list 但它很慢,更重要的是,为了遍历列表,我需要提前知道类型,这是不可能的,因为我不知道是什么调用者可能会传入(除了变量参数必须是原始 C 类型)。

如果解决方案需要 GCC 特定的东西,我也可以接受。

如果解决方案必须放弃可变参数模板,只要解决方案可以迭代变量参数、获取每个参数的类型(helper() 需要信息)并获取每个参数的值。

谢谢!

最佳答案

有一个解决方案,但它涉及到 typeinfo,这可能会影响性能。

#include <iostream>
#include <typeinfo>
#include <cstdarg>
using namespace std;

// This is the function you could puts its implementation in a separate file
// Use only its prototype in the header
void funcWithValist(int count, ...) {
va_list a;
va_start(a, count);
for(int i=0;i<count;i++) {
// Here is an example to extract the type info (you can use anything
// instead of name() )
cout << va_arg(a, std::type_info *)->name() << "\n";
}
}

// The C++ wrapper function, this is to be put in the header file
template<typename... T>
void funcWithArgs(const T&... t) {
funcWithValist(sizeof...(t), (&typeid(t))..., t...);
// Expanded into: the number of args, &typeid(arg1), &typeid(arg2), ...
// arg1, arg2, ...
}

int main() {
// Example of the call
funcWithArgs(4, std::string("Aaa"));
return 0;
}

关于c++ - 如何包装可变参数模板函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52799153/

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