【问题标题】:Macro to get the type of an expression获取表达式类型的宏
【发布时间】:2012-08-28 05:47:45
【问题描述】:

问题

我正在尝试编写一个 C++ 宏,它将以 typetype name 作为输入,并给出 type 作为输出。

例如:
REMOVE_NAME(int)应该是int
REMOVE_NAME(int aNumber)也应该是int

我设法编写了这样一个宏(如下)并且它可以工作,但我想知道我是否缺少一种更简单的方法来完成此操作。

#include <boost/type_traits.hpp>

template <typename T>
struct RemoveNameVoidHelper
{
    typedef typename T::arg1_type type;
};

template <>
struct RemoveNameVoidHelper<boost::function_traits<void()>>
{
    typedef void type;
};

#define REMOVE_NAME(expr) RemoveNameVoidHelper<boost::function_traits<void(expr)>>::type

有什么想法吗?

动机

我正在使用这个宏来帮助生成代码。我有另一个宏,用于在类定义中声明某些方法:

#define SLOT(name, type)                            \
    void Slot##name(REMOVE_NAME(type) argument)     \
    {                                               \
        /* Something that uses the argument. */     \
    }                                               \
    void name(type)

我希望SLOT 宏的用户能够舒适地选择是否要在类内部或外部实现槽,就像使用普通方法一样。这意味着SLOT 的类型参数可以是类型,也可以是具有名称的类型。例如:

class SomeClass
{
    SLOT(ImplementedElsewhere, int);
    SLOT(ImplementedHere, int aNumber)
    {
        /* Something that uses aNumber. */
    }
};

如果没有REMOVE_NAME 宏,我自动生成的Slot... 方法将无法为其参数指定自己的名称,因此无法引用它。

当然,这不是这个宏唯一可能的用途。

【问题讨论】:

  • 是的。更简单的是:不要为此使用宏。或者,如果您这样做,只需单独指定名称?!
  • 查看decltype
  • 为什么?你能用 C++ 11 decltype 吗?
  • decltype(int aNumber) 是非法的,很遗憾。
  • 如果你想要一些“更简单”的东西,如果你能解释一下你想要这个做什么,以及你打算如何使用它,将会有所帮助。

标签: c++ templates types macros typetraits


【解决方案1】:

我认为你是对的;据我所知,唯一的其他生产是 decl-specifier-seqtype-specifier-seq 后跟可选的 declaratorcatch 声明,我认为这对类型提取没有多大用处。 parameter-declaration 也用在 template-parameter-list 中,但也没多大用处。

我可能会这样定义你的宏,消除对 Boost 的依赖:

template<typename T> struct remove_name_helper {};
template<typename T> struct remove_name_helper<void(T)> { typedef T type; };
template<> struct remove_name_helper<void()> { typedef void type; };

#define REMOVE_NAME(expr) typename remove_name_helper<void(expr)>>::type

【讨论】:

  • 谢谢!这确实更好。顺便说一句,你的实现不需要 void 特化 - 只需要解决当函数没有参数时 boost 没有定义 arg1_type 的事实。
猜你喜欢
  • 2016-11-22
  • 1970-01-01
  • 1970-01-01
  • 2020-09-24
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多