c++ define 定义工厂函数,使用##连接

c++ define 定义工厂函数,其中define函数名使用##连接

# include<stdio.h>
# include <stdlib.h>     //atoi
# include <string.h>    //strlen
# include <stdint.h>   //uint64_t
#include<iostream>
#include<memory>
using namespace std;
template <class T>
int DoAllreduce(T tensor, T output) {
    return tensor+output;
}

#define ALLREDUCE(torch_Tensor, THTensor)                                      \
 extern "C" int horovod_torch_allreduce_async_##torch_Tensor(                 \
      THTensor tensor, THTensor output) {           \
      printf("this is all reduce!\n");\
      DoAllreduce(1,1);\
      return 0;                         \
  }

ALLREDUCE(torch_bbyte,int)
ALLREDUCE(torch_bbyte2,int)
int main(){
    horovod_torch_allreduce_async_torch_bbyte(1,1);
    horovod_torch_allreduce_async_torch_bbyte2(1,1);
    return 0;
}

输出:

this is a construc function!
the sum of A is 3
share_ptr:00871244
请按任意键继续. . .

区别#与##

# 是把参数字符串化,## 是将两个参数连为一个整体。

#include <iostream>
#include <cstdlib>

// 测试不带 # 号的效果
#define NO_NUMBER_SIGN(x) x

// 测试一个 # 号的效果
#define SINGLE_NUMBER_SIGN(x) #x

// 测试两个 # 号的效果
#define DOUBLE_NUMBER_SIGN(x, y) x##y

int main()
{   
    // 测试不带 # 号的效果:hello 不加双引号报错(error C2065: “hello”: 未声明的标识符)
    std::cout << NO_NUMBER_SIGN("hello") << std::endl;
    // 测试一个 # 号的效果:world 加不加双引号都可以,因为 # 将其字符串化
    std::cout << SINGLE_NUMBER_SIGN(world) << std::endl;
    // 测试两个 # 号的效果:连接两个对象
    std::cout << DOUBLE_NUMBER_SIGN("hello", "world") << std::endl;
    system("pause");
    return 0;
}

输出:

hello 
world 
helloworld

猜你喜欢

转载自blog.csdn.net/TH_NUM/article/details/81206789