如何使用使用代替定义或其他C++功能
How to use using instead of define or other C++ feature?
在我的代码中,我写了这样一行
#define THREAD_OUTPUT std::cout << "Thread " << thread_index << " - saved " << url << std::endl;
其中thread_index
size_t
,url
std::string
.
当然它可以编译,但我希望它更像C++,因为我知道#define
非常像 C,不建议用于好的C++代码。
这不是一种类型,因此没有基于 using
的替代方法。您可以使用的是一个函数。下面是一个使用 lambda 的示例:
auto THREAD_OUTPUT = [&]() {
std::cout
<< "Thread"
<< thread_index
<< " - saved "
<< url
<< std::endl;
};
用法略有不同:
THREAD_OUTPUT();
P. S. 考虑是否使用 std::endl
是必要的或有用的。不冲洗可能更有效。
你的意思是,比如,一个函数?
void ThreadOutput(const std::size_t thread_index, const std::string& url)
{
std::cout << "Thread " << thread_index << " - saved " << url << std::endl;
}
我什至想让它更笼统一点:
void ThreadOutput(std::ostream& os, const std::size_t thread_index, const std::string& url)
{
os << "Thread " << thread_index << " - saved " << url << std::endl;
}
// ThreadOutput(std::cout, 42, "https://lol.com");
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 在其他文件中创建类时在 c++ 项目中不起作用
- 类与私有变量的其他类之间的线程安全性
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- GlobalAlloc而不是其他分配方法
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 断言中的Fold表达式在某些计算机上编译,但在其他计算机上不编译
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 结构和双指针隐藏在其他结构中,多层混淆
- UE4在OnComponentBeginOverlap上铸造其他actor
- 当我在其中一个线程执行中(在activemq-cpp中)捕获到特定值时,我如何终止/停止所有其他线程
- MESI协议和std::atomic-它是否确保所有写入立即对其他线程可见?
- 保留对其他类的成员函数的引用
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 具有包含其他对象的类的对象创建顺序
- 让bool方法返回其他整数