如何使用使用代替定义或其他C++功能

How to use using instead of define or other C++ feature?

本文关键字:其他 C++ 功能 定义 何使用      更新时间:2023-10-16

在我的代码中,我写了这样一行

#define THREAD_OUTPUT std::cout << "Thread " << thread_index << " - saved " << url << std::endl;

其中thread_index size_turl 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");
相关文章: