在C++中实现内联代码的方法是什么?我只能考虑宏和内联函数。在C++11/17/20 (例如lambda)中是否有更多的替代方案?利害得失?
// do macros still make sense in modern C++ standards?
#define square(x) ((x)*(x))
// is this a good alternative to macros?
template <class T> inline T square(T x) { return x * x; }编辑:修改后的评论为“宏是否仍然被鼓励.?”“宏仍然有意义吗.”
发布于 2021-02-10 11:02:45
// is this a good alternative to macros?
template <class T> inline T square(T x) { return x * x; }是的,这是首选的方法。(虽然模板一般不需要内联,而显式模板专门化和实例化则需要,但保持一致性并写出一个含义是可以的。)
还请注意,constexpr函数和构造函数是隐式内联的。
还请注意,在虚拟重载的上下文中使用final (在适当情况下)可以帮助内联甚至一些虚拟方法(请查看此帖子以获得一些示例和解释)。
发布于 2021-02-10 11:00:05
宏有一个很大的优势:它们与名称空间无关。
想象一下如果我扩展你的样本会发生什么:
// are macros still encouraged in modern C++ standards?
#define square(x) ((x)*(x))
namespace My {
int square(int x) { return x * x; }
} // namespace My所以,IMHO,答案是否定的。
请记住,在C(引入了预处理器的地方)中,没有名称空间,直到现在还没有添加名称空间。
演示:
#define square(x) ((x)*(x))
namespace My {
int square(int x) { return x * x; }
} // namespace My预处理:
namespace My {
int ((int x)*(int x)) { return x * x; }
}
int main()
{
std::cout << My::((10)*(10));
}coliru演示
反对:
#include <iostream>
template <typename T>
T square(T x) { return x * x; }
namespace My {
int square(int x) { return x * x; }
} // namespace My
int main()
{
std::cout << My::square(10);
}输出:
100coliru演示
发布于 2021-02-10 11:00:31
宏从未被鼓励过。请考虑宏所做的与函数不同的操作,例如:
int foo() {
static int x = 0;
++x;
return x;
}
std::cout << square(foo());这只是宏观经济的一个不利因素。如果您想要一个接受参数并返回值的函数,那么它不是宏。
https://stackoverflow.com/questions/66135466
复制相似问题