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???
Can we rename cout, endl keyword in cpp?
Neither cout
nor endl
are keywords in C++. They are names declared in std
namespace of the standard library. Former is a variable and latter is a function template.
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:
auto& some_name = std::cout;
For function templates, an option is to write a wrapper function template:
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
:
#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& print = std::cout;
Some important notes:
You can't create aliases of std::cout
, std::endl
, etc. with using
statement.
Since std::endl
is a template function and not a type, it can't be deduced using the reference to auto type.
OTOH, you can use #define
statements (C like):
#include <iostream>
#define print std::cout <<
#define end << std::endl
.
.
print "Hello world!" end;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.