【问题标题】:Function Definition Generation from Declaration using Template Metapogramming使用模板元图从声明生成函数定义
【发布时间】:2018-08-25 23:18:20
【问题描述】:

C++ 大师,

我有一个模板元编程问题。考虑以下 函数声明。

int foo(const int x[], char *y, size_t size);

我希望能够生成如下函数体:

int foo(const int x[], char *y, size_t size)
{
  return myfnc(x, y, size);
}

有没有办法用 C++ 模板元编程来做到这一点?我能 在一些宏中“包装”声明,但我想避免使用 宏来做完整的扩展。例如,如果 我可以写一些类似的东西:

DEFINE_FNC(foo, const int x[], char *y, size_t size)

DEFINE_FNC 定义为

#define DEFINE_FNC(fnc, ...) \
int fnc(__VA_ARGS__) {       \
  return myfnc(__VA_ARGS__); \ // This doesn't work; is there something else that can be done here?
}                            \

我知道here 提到的解决方案,但这需要我 在参数类型周围添加括号,我想 如果可能的话,避免这种情况。

我尝试使用可变参数模板,但效果并不理想 我要。

【问题讨论】:

  • XY 问题?解释你真正想要完成的事情。
  • “这需要我在参数类型周围添加括号,” ...您还希望预处理器如何获得const int x [] 中的x? (在 C++ 中,你真的应该更喜欢可变参数模板方法)。

标签: c++ templates variadic-templates template-meta-programming variadic-macros


【解决方案1】:
template <typename Args...>
int foo(Args&&... args) {
  return myfnc(std::forward<Args>(args)...);
}

如果你愿意的话,你可以用一个宏来删除这些定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-18
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多