gpt4 book ai didi

c++ - 获取表达式类型的宏

转载 作者:可可西里 更新时间:2023-11-01 16:46:34 26 4
gpt4 key购买 nike

问题

我正在尝试编写一个 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... 方法将无法为其参数指定自己的名称,因此也无法引用它。

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

最佳答案

我认为你是对的;据我所知,唯一的其他产品是 decl-specifier-seqtype-specifier-seq 后跟可选的 declarator是一个 catch 语句,我认为这对类型提取没有多大用处。 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

关于c++ - 获取表达式类型的宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12248717/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com