简体   繁体   English

预处理器宏中的typedef

[英]typedef in Preprocessor macro

I have a macro definition like this, to easily create a shared_ptr for a class: 我有一个这样的宏定义,可以轻松地为一个类创建一个shared_ptr:

#define create_ptr(__TYPE__) typedef std::shared_ptr<__TYPE__>

What I want to now is to append "Ptr" to the class name, so that 我现在想要的是在类名后附加“ Ptr”,这样

create_ptr(MyClass)

would result in a typedef named MyClassPtr as std::shared_ptr<MyClass> How would I accomplish this? 会导致一个名为MyClassPtrtypedef作为std::shared_ptr<MyClass>怎么做?

You need token concatenation ## 您需要令牌串联##

#define create_ptr(__TYPE__) typedef std::shared_ptr<__TYPE__> __TYPE__ ## Ptr;

class Foo{
public:
};

create_ptr(Foo)

FooPtr foo;

For detailed explanation have a look here https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html 有关详细说明,请参见此处https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html

An alternative route is a using declaration: 另一种途径是使用声明:

template <typename T>
using sp = std::shared_ptr<T>;

sp<int> my_shared_int_pointer ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM