为可变参数模板函数中的每个模板类型调用 void 函数? [英] Call void function for each template type in a variadic templated function?

查看:38
本文介绍了为可变参数模板函数中的每个模板类型调用 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));
}

演示.

这篇关于为可变参数模板函数中的每个模板类型调用 void 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆