如果有括号,有没有办法使宏具有不同的行为
Is there a way to make a macro have different behavior if it has parenthesis?
我正在尝试做这样的事情:
#define FOO printf("No parenn");
#define FOO(x) printf(x);
有没有办法使用 c++ 宏来做到这一点?
No. 给定的宏名称可以是纯的("类似对象")或"类似函数",而不是两者兼而有之。
我不建议这样做,但在C++本身的帮助下是可能的,
#include <iostream>
template<typename T>
struct CustomMessage
{
const T& t;
CustomMessage(const T& t) : t(t)
{}
};
struct DefaultMessage
{
template<typename T> CustomMessage<T> operator() (const T& t)
{
return {t};
}
};
template<typename T>
std::ostream& operator<< (std::ostream& os, const CustomMessage<T>& message)
{
return os << message.t;
}
std::ostream& operator<< (std::ostream& os, const DefaultMessage& message)
{
return os << "no parenn";
}
using namespace std;
#define FOO std::cout << DefaultMessage{}
int main() {
int x = 42;
FOO;
FOO(x);
return 0;
}
活一个 Ideone https://ideone.com/VboP8R
不是那么直接:单个宏必须是"普通"或"类似函数"。
但是,你可以朝这个方向做一些事情。
您可以使用可变参数宏并根据参数的数量更改行为。
您可以使用上述内容构建要委派给的目标宏的名称:
#define NUM_ARGS_(_10, _9, _8, _7, _6, _5, _4, _3, _2, _1, N, ...) N
#define NUM_ARGS(...) NUM_ARGS_(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define CONCAT_(a, b) a##b
#define CONCAT(a, b) CONCAT_(a, b)
#define CAKE_1(X) some-interesting-code-here
#define CAKE_2(X, Y) some-different-interesting-code-here
#define CAKE(...) CONCAT(CAKE_, NUM_ARGS(__VA_ARGS__))(__VA_ARGS__)
在上面,用 1 个参数调用 CAKE() 将调用CAKE_1,用 2 调用它将调用CAKE_2。
出于清晰等原因,做这种事情是否是一个好主意,留给读者作为练习。
相关文章:
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 遇到新行时,有没有办法停止istream_iterator
- 有没有办法在 c++ 中同时生成随机数?如果没有,是否有解决方法?
- C++如果采用类类型的函数被传递派生类型,有没有办法给出错误?
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- 有没有办法我可以在 C++ 中使用 if 语句来说明如果一个字符串不是两个名称的 eqal,它会给出一个输出,ATM i
- 有没有办法搜索向量的元素,<String>然后检查它是否包含特定的字符,如果它确实打印了它
- 有没有办法找到任意类类型的直接基类(如果有的话)?
- 如果函数的返回值将用作右值引用而不是左值,有没有办法使函数具有不同的行为?
- 如果我有一个将指针变量作为输入的函数,有没有办法将函数作为参数传递
- 如果文件/目录大小增加以上,有没有办法在Linux中重新呼叫
- 有没有无法锁定(提升为shared_ptr)的weak_ptr?如果没有,为什么?
- 如果有括号,有没有办法使宏具有不同的行为
- C ++unordered_map有没有办法为元素预先分配内存,如果事先知道最大大小
- 有没有一种方法可以将现有函数用作类的一部分?如果是,如何
- 如果我创建一个列表:<T>:迭代器,有没有办法重载++(增量)运算符?
- 有没有办法从 boost::any 中获取一个整数,如果您不知道原始类型是有符号的还是无符号的