为可变参数模板函数中的每个模板类型调用 void 函数?
我的目标是编写一个简单的通用函数,用于为任意 C++ 类型注册转换器.为简单起见,我将只打印 C++ 类型名称.我希望能够为任何类型调用我的通用 print_type_name
函数,包括一次多种类型(可变参数):
My goal is to write a simple generic function for registering converters for arbitrary C++ types. For simplicity I'll just print C++ type names. I'd like to be able to call my generic print_type_name
function for any types, including multiple types at once (variadic):
template <typename T>
void print_type_name(void)
{
std::cout << typeid(T).name() << std::endl;
}
这适用于这样的事情:
print_type_name<int>();
print_type_name<std::string>();
print_type_name<std::vector<std::complex<float> > >();
但是,我需要能够为可变参数模板中的每种类型调用此函数,例如(展开时):
However, I need to be able to call this function for each type in a variadic template, e.g. (when expanded):
print_type_name<int, std::string, std::vector<std::complex<float> > >();
这是我想出来的,但它相当笨重:
Here's what I've come up with, but it's rather clunky:
template <typename ...TS>
void noop(TS... ts) { }
template <typename T>
int real_print_type_name(void) {
std::cout << typeid(T).name() << std::endl;
return 0;
}
template <typename ...TS>
void print_type_name(void) {
noop(real_print_type_name<TS>()...);
}
允许以下内容:
template <typename ...TS>
void other_function(void) {
print_type_name<TS...>();
}
注意无用的 noop
函数和 int
返回类型real_print_type_name
,这两个我都必须添加才能扩展参数包.有没有更干净的方法来做到这一点?
Notice the useless noop
function and the int
return type of
real_print_type_name
, both of which I had to add in order to expand
the parameter pack. Is there a cleaner way of doing this?
template <typename ...TS>
void print_type_name() {
using expander = int[];
(void) expander{ 0, (std::cout << typeid(TS).name() << '\n', 0)... };
}
或者,C++17 风格:
Or, C++17-style:
template <typename ...TS>
void print_type_name(void) {
(std::cout << ... << (typeid(TS).name() + "\n"s));
}
演示.