Can we rename cout, endl keyword in cpp? - c++

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;

Related

Can I use a std::string variable as an argument to an operator?

For example, if I have:
#include <iostream>
using namespace std;
int main()
{
int b = 1;
int c = 2;
string a = "(b + c)";
cout << (4 * a) << "\n";
return 0;
}
Is it possible to have string a interpreted literally as if the code had said cout << (4 * (b + c)) << "\n";?
No. C++ is not (designed to be) an interpreted language.
Although it's theoretically possible to override operators for different types, it's very non-recommended to override operators that don't involve your own types. Defining an operator overload for std::string from the standard library may break in future. It's just a bad idea.
But, let's say you used a custom type. You could write a program that interprets the text string as a arithmetic expression. The core of such program would be a parser. It would be certainly possible, but the standard library doesn't provide such parser for you.
Furthermore, such parser wouldn't be able to make connection between the "b" in the text, and the variable b. At the point when the program is running, it has no knowledge of variable names that had been used to compile the program. You would have to specify such information using some form of data structure.
P.S. You forgot to include the header that defines std::string.
#include<string>
///...
auto a=std::to_string(b+c);
std::cout<<4*std::stoi(a)<<std::endl;
You can just use std::string and std::stoi.

Accessing active union member

Is there a simple way to understand which union member is active?
An example:
union Read_Value{
char ch;
float number;
string str;
}
Suppose a void function reads from an input file stream and initialise Read_Value on the base of the type of the variable read. Assuming I don't know how the function works, how can I understand which of the three member is active?
A bare union cannot tell you which is the active element. You have to keep track of that yourself.
Since C++17 std::variant is the "modern union". It has a index() method that tells you which is the active index. Example from cppreference:
#include <variant>
#include <string>
#include <iostream>
int main()
{
std::variant<int, std::string> v = "abc";
std::cout << "v.index = " << v.index() << '\n';
v = {};
std::cout << "v.index = " << v.index() << '\n';
}
Possible output:
v.index = 1
v.index = 0
Is there a simple way to understand which union member is active?
In general, using a tagged (or discriminated) union. This means storing some metadata (tracking which member is active) alongside the raw union.
The modern solution is indeed std::variant, which does all this for you.
If you don't have C++17 support, don't have it in your standard library's experimental or tr extensions, and for some reason can't use the Boost.variant precursor ... you can still write an old-style tagged union yourself.
I wouldn't call it simple though, at least not to do well.

c++ implicit type conversion string -> int?

I was just working on c++ types, when i just thought of trying out the following program.
void swap(int& a, int& b){
int temp = a;
a = b;
b = temp;
}
int main(){
string a{"sssss"}, b{"ddddd"};
swap(a,b); //this should not work!! but it does
cout << a << ' '<<b <<endl;
return 0;
}
I was not expecting this to swap the strings, but it does! Why is this working? Although the compiler raises warnings, it is not an error!
Your program does not compile. I am guessing that you actually had the following lines but failed to post them:
#include <iostream>
#include <string>
using namespace std;
There is a standard template std::swap. Although this is in #include <algorithm>, any header may include any other header. So even if you didn't include this specifically, it may have gotten included anyway.
So when you call an unqualified swap, both your swap and std::swap are included in overload resolution. (Even if you didn't have using namespace std;, namespace std is still searched because of ADL, since the arguments are of type std::string which is in namespace std).
To avoid this happening, you could put your swap in a named namespace, and use the qualified name (e.g. mystuff::swap(a, b);).
// Assuming the following:
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
// or even using namespace std, though this
// would make std::swap a candidate even
// without ADL
// renaming shows that it's not this function
// that gets called ...
void myswap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
// printing some output also reveals what's going on
}
int main() {
string a{"sssss"}, b{"ddddd"};
swap(a,b); // this is not calling your swap!
// myswap(a,b) produces the error you expected
cout << a << ' '<< b <<endl;
return 0;
}
It's not calling your swap function. Namespaces are kind of interfaces, so when one declares free functions to be in the same namespace as the data types they operate on, then calling them without proper namespace qualification will work.
This is called "argument dependent name lookup", or ADL.
So when you call the function swap on a std::string, it'll also look for candidates in the std namespace. And since there's std::swap, which can be applied to strings and no other candidate in your global namespace (since your swap only operates on integers) it'll use it for the call.
As I showed above you can make your function produce debugging output or rename it to easily verify that it's not your function that is called.
As a side note: Suppose there were some kind of implicit conversion from string to int. You'd then get two temporaries. Then your swap function would get called (not in reality, since binding non const references to temporaries isn't allowed) and these integers exchanged. And then? This wouldn't have any effect on the original strings.
Finally, I wouldn't count this code as portable. It only compiles when either the header string or iostream includes the algorithm header, and one of these three provides the specialisation of std::swap for strings. But since this doesn't seem to be guaranteed by the standard, this code would only reliably work when including algorithm yourself.

Template class in c++?

I am using a template class to set the data type for a swap function. In the code if i initialize the function name as lower case letter it throws an error
call of overloaded 'swap(double&, double&) is ambiguous
but when i initialize the function name as upper case it works fine.
Will appreciate if someone could explain me why this is happening. Here is my code
#include<iostream>
using namespace std;
template <class T>
void swap(T &a,T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
int main()
{
double value1 = 2.44;
double value2 = 6.66;
cout<<"\tBefore swap \n";
cout<<"Value 1 = "<< value1 <<"\tValue 2 = " << value2 <<"\n";
swap(value1,value2);
cout<<"\tafter swap \n";
cout<<"Value 1 = "<< value1 <<"\tValue 2 = "<<value2;
}
Instead of
swap(value1,value2);
use
::swap(value1,value2);
This would solve the namespace and ambiguity issue.
because there is already a standard library function std::swap http://www.cplusplus.com/reference/algorithm/swap/ so possibly your compiler does not like it? You pull that in via using namespace std;
Change the name of your swap function because std::swap already exists.
Or you could put it in a separate namespace and use the scope resolution operator, "::", to distinguish yours from the standard one.
This is what happens when you use namespace std;. You may want to be more specific and use:
using std::cout;
using std::endl;
using std::cin;
Already standard library function is defined with templates 'swap' Instead of 'SWAP',It is actually under the std namespace, but because you have a using namespace std line, it exists without the std:: prefix.
As you can see, using the using namespace std isn't always a good option because of possible name collisions, as in this example. In general one should prefer not to use the using directive unless there's a real reason for this - namespaces exist for a reason - to prevent name collisions.

Overload operator<< (unsigned char typedef as byte)

I want to overload (hijack?) ostream and basic_ostream<unsigned char> so that it stops attempting to display an octet (unsigned char) as a printable character.
I've been living with cout and friends putting smiley faces on the screen for far too long. And I'm tired of working around with casts: hex << int(0xFF & b) << ....
Is it possible to override the standard behavior? I've tried both template and non-template overrides. They compile, but do not appear to be called.
The problem is that there already is a
template<class charT, class traits>
std::basic_ostream<charT,traits>&
operator<<(std::basic_ostream<charT,traits>&, charT);
in namespace std. Since basic_ostream<> is also in this namespace, ADL picks it up when you output an unsigned char. Adding your own overload might make calling the operator ambiguous, or your overload will silently be ignored.
But even if it would work, it would be brittle, because forgetting one include might subtly alter the meaning of the code without any diagnostic from the compiler.
And there's more: Every maintenance programmer looking at such code will assume the standard operator is called (and never think of adding an include when he adds another output statement to the code).
In short, it might be best to add a function doing what you want to do.
A reasonable semantic alternative to that might be to add a stream manipulator that invokes the output format you want. I'm not sure if that's technically possible, though.
Luc is correct.
A quicker alternative to your current approach — if you don't mind decimal output — is to promote the char to int:
unsigned char c = '!';
os << +c;
I don't see how this would be taxing!
#include <iostream>
#include <string> // std::char_traits
typedef unsigned char UChar;
typedef UChar Byte;
typedef std::char_traits<char> CharTraits;
typedef std::char_traits<wchar_t> WCharTraits;
typedef std::basic_ostream< char, CharTraits > CharOStream;
typedef std::basic_ostream< wchar_t, WCharTraits > WCharOStream;
CharOStream& operator<<( CharOStream& stream, UChar v )
{
return stream << v+0;
}
int main()
{
char const c = 'c';
UChar const u = 'u';
std::cout << c << '\n' << u << std::endl;
}
This works nicely with MSVC 10.0 and MinGW g++ 4.4.1, and it compiles cleanly with Comeau Online, so I believe it's formally OK.
Cheers & hth.,
Als is right that what you're asking for isn't going to happen.
The best you can do is to write your own IO manipulator (iomanip) to do the magic for you. In this case, you need a function that takes an unsigned char (though I'd strongly recommend using uint8_t from <stdint.h>).
#include <stdint.h>
#include <ostream>
class asHex
{
public:
asHex(uint8_t theByte): value(theByte) {}
void operator()(std::ostream &out) const
{ std::ios::fmtflags oldFlags = out.flags; out << std::hex
<< std::setw(2) << std::setfill('0') << std::uppercase << theByte;
out.flags(oldFlags); }
private:
uint8_t theByte;
};
std::ostream& operator<<(std::ostream &out, asHex number)
{
number(out); return out;
}
Then you can write:
cout << asHex(myByte);
You can add constructors to asHex or even make it a template class to support 16, 32, and other bit counts.
(Yes, I know <stdint.h> is not an official C++ header, but I'd rather have its definitions in the global namespace instead of std:: without having to do a using namespace std; which dumps everything in the global namespace.)
Due to ADL the standard operator<< will be called. Try to explicitly qualify your call:
::operator<<(os, 42);
You cannot override the behavior of std::cout directly. It would be too error-prone if any dev code can change the behavior of the standard library used by other code.
You can create your own class that emulates the behavior of std::cout and use that object instead.
class SpecialCout
{
template <typename T>
friend SpecialCout& operator<< ( SpecialCout const& scout, T const &t )
{
// Do any adjustments to t here, or decide to return early.
std::cout << t;
return *this;
}
};
extern SpecialCout scout;