问题描述
我正在尝试编写一个将 type
或 type name
用作输入的C ++宏,并提供 type
作为输出.
I am trying to write a C++ macro that would take either type
or type name
as input, and give type
as output.
例如:REMOVE_NAME(int)
应该是int
REMOVE_NAME(int aNumber)
也应该是int
For example:REMOVE_NAME(int)
should be int
REMOVE_NAME(int aNumber)
should also be int
我设法编写了一个这样的宏(在下面),它可以工作,但是我想知道我是否缺少一种更简单的方法来实现这一目标.
I managed to write such a macro (below) and it works, but I'm wondering whether I'm missing a simpler way to accomplish this.
#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
有什么想法吗?
我正在使用此宏来辅助代码生成.我还有另一个宏,用于在类定义中声明某些方法:
I'm using this macro to aid with code generation. I have another macro which is used to declare certain methods in class definitions:
#define SLOT(name, type) \
void Slot##name(REMOVE_NAME(type) argument) \
{ \
/* Something that uses the argument. */ \
} \
void name(type)
我希望SLOT
宏的用户能够舒适地选择是要在类的内部还是外部实现其插槽,就像使用普通方法一样.这意味着SLOT
的type参数可以是类型,也可以是带有名称的类型.例如:
I want the user of the SLOT
macro to be able to comfortably choose whether he wants to implement his slots inside or outside the class, just like with normal methods. This means that SLOT
's type argument can be either a type, or a type with a name. For example:
class SomeClass
{
SLOT(ImplementedElsewhere, int);
SLOT(ImplementedHere, int aNumber)
{
/* Something that uses aNumber. */
}
};
没有REMOVE_NAME
宏,我自动生成的Slot...
方法将无法为其参数指定其自己的名称,因此将无法引用它.
Without the REMOVE_NAME
macro, my automatically generated Slot...
method will not be able to specify its own name for its argument, and thus it will not be able to refer to it.
当然,这不是此宏的唯一可能用途.
Of course, this is not the only possible use for this macro.
推荐答案
我认为您是正确的;据我所知,只有其他生产中,在 decl-specifier-seq 或 type-specifier-seq 之后是可选的 declarator 是catch
语句,我认为类型提取没有太大用处.生产 parameter-declaration 也用在 template-parameter-list 中,但这也没什么用.
I think you're correct; as far as I can tell the only other production where a decl-specifier-seq or type-specifier-seq is followed by an optional declarator is a catch
statement, and I don't think that's much use for type extraction. The production parameter-declaration is also used in template-parameter-list, but that's not much use either.
我可以这样定义您的宏,从而消除对Boost的依赖:
I might define your macro like this, removing the dependency on 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
这篇关于宏以获取表达式的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!