c++ - 推断声明的类型

标签 c++ macros type-deduction

我正在编写一个将声明作为其单个参数的宏。是否可以在宏内部推断声明的类型而不将单个参数拆分为单独的类型标识符参数?

#define M(declaration) \
    declaration;       \
    static_assert(sizeof(/* deduce type of 'declaration' */) == 4, "!")

M(int i);
M(double d{3.14});
M(std::string s{"Hello, world!"});

以下实现可以工作,但感觉不太用户友好(imo):

#define M(type, identifier) \
    type identifier;        \
    static_assert(sizeof(type) == 4, "!")

M(int, i);
M(double, d{3.14});
M(std::string, s{"Hello, world!"});

如果可能的话,我更愿意将声明作为一个参数。


相关问题: Macro to get the type of an expression ;但我未能让该代码在我的示例中工作(编译器错误:expected nested-name-specifier)。

最佳答案

如果您的静态断言消息真的那么简单 "!"1,我建议您放弃预处理器。让类型系统为你工作:

namespace detail {
  template<typename T>
  struct check_declared_type {
    using type = T;
    static_assert(sizeof(type) == 4, "!");
  };
}

template<typename T>
using M = typename detail::check_declared_type<T>::type;

// .. Later

int main() {
  M<int> i;
  M<double> d{3.14};
  M<std::string> s{"Hello, world!"};
}

<子> 1 - 具体来说,如果您不需要预处理器为您对任何内容进行字符串化。

关于c++ - 推断声明的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47014565/

相关文章:

c++ - 无法使用内联功能的时间

java - 在 Java 中针对接口(interface)进行编程与在 C/C++ 中使用头文件的概念相同吗?

C++ 泛型 lambdas : pattern type deduction

c++ - 在扣除 auto 之前使用 decltype(auto) <func>

c++ - 元启发式洗牌

c++ - 帮助完成半复杂的 C++ 赋值

c - 为什么 _Generic 语句被视为表达式而不是宏?

c++ - 如何标记粘贴号码?

c - printf 给出错误的输出

c++ - 从函数指针作为模板参数的类型推导