有没有一种方法来定义可变参数模板宏? [英] Is there a way to define Variadic template macro?

查看:54
本文介绍了有没有一种方法来定义可变参数模板宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以像可变参数宏一样定义可变参数模板宏?

Is there a way to define variadic template macro just like variadic macro?

例如,如果定义可变参数宏,例如:

For example, if define variadic macro like:

#define PRINT_STRING(fmtId, ...) { \
    CString fmt; \
    fmt.FormatString(fmt, ##__VA_ARGS__); \
    cout << fmt << endl; }

我们可以定义以下内容吗?

Could we define something like:

#define PARSE_FUNCTION(functionName, typename...) \
    std::function<int(typename...)> m_##functionName(){ \
        return (std::function<int(typename...)>) functionName; }


推荐答案

__ VA_ARGS __ 可以使用多次,所以您可以这样写:

__VA_ARGS__ can be used multiple times, so you could write:

#define PARSE_FUNCTION(functionName, ...) \
    std::function<int(__VA_ARGS__)> m_##functionName() { \
        return std::function<int(__VA_ARGS__)>(functionName); \
    }

发生的事情只是简单的文本替换,无论参数是否为

What is happening is just simple text substitution, whether the arguments is for a template or not won't be checked by the preprocessor.

实际上,任何函数对象都可以隐式转换为 std :: function ,因此可以省略强制类型转换。此外,如果 functionName 引用函数指针,则可以轻松推断出确切的类型,从而根本不需要可变参数宏:

Actually any function objects can be implicitly converted to a std::function, so the cast can be omitted. Furthermore, if functionName refers to function pointers, the exact type can be easily inferred, that you don't need the variadic macro at all:

#define PARSE_FUNCTION(functionName) \
    auto m_##functionName() \
        -> std::function<std::remove_pointer<decltype(functionName)>::type> \
    { \
        return functionName; \
    }

这篇关于有没有一种方法来定义可变参数模板宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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