簡體   English   中英

使用 C++ 宏注冊模板 class 和別名

[英]Using C++ macros to register a template class and an alias

假設我有以下代碼。

namespace foo{
template <typename A>
struct Foo{};
}

struct Bar{};

struct Baz{};

我想編寫一個宏CREATE來創建一個新的CustomName1Type class 和CustomName2Type class。

#define CREATE(custom_name, struct_name)         \
template class foo::Foo<struct_name>;            \ 
using #custom_name##Type = foo::Foo<struct_name>;

CREATE(CustomName1, Bar)
CREATE(CustomName2, Baz)

等於

template class foo::Foo<Bar>;
using CustomName1Type = foo::Foo<Bar>;

template class foo::Foo<Baz>;
using CustomName2Type = foo::Foo<Baz>;

我如何修改CREATE來做到這一點? 另外,編寫這樣一個宏的樣式指南要求和 position 是什么?

我如何修改CREATE來做到這一點?

#include <iostream>
#include <type_traits>
#include <cstdint>

using namespace std;

#define JOIN(A, B) A##B

#define CREATE(custom_name, struct_name) \
template class foo::Foo<struct_name>; \
using JOIN(custom_name, Type) = foo::Foo<struct_name>; 

namespace foo{
template <typename A>
struct Foo{};
}

struct Bar {};

struct Baz {};

CREATE(CustomName1, Bar)
CREATE(CustomName2, Baz)

int main() {

  cout << is_same<CustomName1Type, foo::Foo<Bar>>::value << endl;
  cout << is_same<CustomName2Type, foo::Foo<Baz>>::value << endl;
}

另外,編寫這樣一個宏的樣式指南要求和 position 是什么?

我不明白這部分,但我認為它指的是為什么你的宏不起作用(如果我錯了,請告訴我我會編輯答案)


問題是: using #custom_name##Type = foo::Foo<struct_name>;

因為您沒有任何名為 Type 的參數,請參見下面的示例:

#define CONCAT1(A, B) A##B -> This will join A and B

#define CONCAT2(A, B) #A -> This will replace A parameter as caractere ("")

#define CONCAT3(A, B) #A#B -> This will join A and B parameter as caractere ("")

int main(){
  int MyValue = 100;
  cout << CONCAT1(My, Value) << endl; //cout << MyValue << endl

  cout << CONCAT2(My, Value) << endl; //cout << "My" << endl

  cout << CONCAT3(My, Value) << endl; //cout << "MyValue" << endl
}

結果:
100
我的
我的價值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM