简体   繁体   English

我们可以在 cpp 中重命名 cout、endl 关键字吗?

[英]Can we rename cout, endl keyword in cpp?

As typedef can give change names of types and define can make an alias for values and functions, Is there any way to change the name of cout, endl etc???由于 typedef 可以更改类型的名称,而 define 可以为值和函数创建别名,有没有办法更改 cout、endl 等的名称?

Can we rename cout, endl keyword in cpp?我们可以在 cpp 中重命名 cout、endl 关键字吗?

Neither cout nor endl are keywords in C++. coutendl都不是 C++ 中的关键字。 They are names declared in std namespace of the standard library.它们是在标准库的std命名空间中声明的名称。 Former is a variable and latter is a function template.前者是一个变量,后者是一个 function 模板。

You cannot "rename" variables nor function templates any more than you can rename types, but like you can create an alias for types, you can essentially achieve the same for variables using a reference:您不能“重命名”变量或 function 模板,就像您可以重命名类型一样,但是就像您可以为类型创建别名一样,您基本上可以使用引用为变量实现相同的目的:

auto& some_name = std::cout;

For function templates, an option is to write a wrapper function template:对于 function 模板,一个选项是编写一个包装器 function 模板:

template<class CharT, class Traits>
auto&
endl_wrapper(std::basic_ostream<CharT, Traits>& os)
{
    return std::endl(os);
}

Avoid obfuscating the program with unnecessary aliases.避免使用不必要的别名混淆程序。

Two ways to do that.有两种方法可以做到这一点。 In C++ sense, you could use std::ostream :在 C++ 意义上,您可以使用std::ostream

#include <iostream>
std::ostream& alias = std::cout;

Or, in a better manner, use reference to auto to let the compiler decide the correct type.或者,以更好的方式,使用对auto的引用让编译器决定正确的类型。

auto& print = std::cout;

Some important notes:一些重要的注意事项:

  1. You can't create aliases of std::cout , std::endl , etc. with using statement.您不能using语句创建std::coutstd::endl等的别名。

  2. Since std::endl is a template function and not a type, it can't be deduced using the reference to auto type.由于std::endl是模板 function 而不是类型,因此无法使用对自动类型的引用来推断。


OTOH, you can use #define statements (C like): OTOH,您可以使用#define语句(类似C):

#include <iostream>
#define print std::cout <<
#define end   << std::endl
.
.
print "Hello world!" end;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM