是否可以将宏扩展为两个不同类型的数据



更新

原来的问题似乎没有那么清楚,所以我又举了一个例子来说明我需要什么。

#define RPC_FUNC(X) &X,???   // I don't know how...
class Test {
public:
static void func(int a) {}
};

int main()
{
const auto ptr1 = std::make_pair(&Test::func, "Test::func");
// const auto ptr2 = std::make_pair(RPC_FUNC(Test::func));
// ptr2.first(123);  // this should call the function Test::func
// std::cout << ptr2.second; // this should print the string "Test::func"

return 0;
}

如何定义宏RPC_FUNC以使此代码正常工作?意味着我想使ptr1ptr2完全相同。

原件

我想做一段这样的代码:

template<typename F> // F is the type of some functions
void func(F f, const std::string& funcMark) {
// do something
}

我想将一个非静态成员函数和一个字符串传递到函数func中。

有时,第二个参数只是第一个参数的名称。让我们看一个例子:

namespace sp {
class Test {
public:
void doJob() {}
};
}
func(&sp::Test::doJob, "doJob");

我想做的是这样做上面的调用:func(MY_MARCO(sp::Test::doJob))

也就是说,宏MY_MACRO应该将其参数sp::Test::doJob扩展为&sp::Test::doJob, "doJob"

宏应该精确执行的规范是模糊的。字符串化运算符#可以将宏参数转换为字符串文字:

// example code what it does
#include <iostream>
#define YOUR_MACRO(X) X() << " from " << #X "()"
int foo() { return 42; }
int main() { std::cout << YOUR_MACRO(foo) << std::endl; }

输出

42来自foo()

将字符串文字转换为std::string也很简单:

#include <iostream>
#include <string>
#define YOUR_MACRO(X) X() << " from " << std::string(#X "()")
int foo() { return 42; }
int main() { std::cout << YOUR_MACRO(foo) << std::endl; } 

工作原理相同。你被困在哪里了?

更新

规范现在好多了!但是它基本上和我已经发布的一样,你应该在宏中使用字符串运算符#:

#include <iostream>
#define RPC_FUNC(X) &X, #X
class Test {
public:
static void func(int a) {
std::cout << "called Test::func(" << a << ")" << std::endl;
}
};
int main() {
const auto ptr1 = std::make_pair(&Test::func, "Test::func"); // gets warning about unused variable
const auto ptr2 = std::make_pair(RPC_FUNC(Test::func));
ptr2.first(123);  // prints "called Test::func(123)"
std::cout << ptr2.second << std::endl; // prints "Test::func"
return 0;
}

最新更新