cout uint8_t as integers instead of chars - c++

#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
cout << (uint8_t)123 << endl;
}
This will output { , since {'s ASCII is 123.
But I want to get 123 instead. I found cout << (int)123 << endl; will do this, but I'm not willing to cast uint_8 to int every times. Can I configure cout to achieve this?

I definitely do not condone the solution I am about to suggest. I also suspect that it may not be permitted by the standard, but I cannot prove it, as of yet. If someone can provide me a reference that shows that it is not permitted, then I will delete this answer. Anyway, my tests so far indicate that simply overloading the operator in the global scope seems to work.
#include <iostream>
#include <cstdint>
std::ostream & operator<<(std::ostream & os, std::uint8_t val)
{
return os << static_cast<int>(val);
}
int main()
{
std::uint8_t val = 123;
std::cout << val;
}
I wouldn't have thought this would work, but then I realized that the char/unsigned char/signed char overloads for operator<< are all free functions in the std namespace picked up by ADL. And I guess global functions are considered a better match than ADL functions, but I'm not sure about that.

Related

Implicit casting acting strange

I have a question about implicit casting for the following code
#include <iostream>
using namespace std;
float max(int a, int b)
{
if (a > b)
return a;
else return b;
}
int main() {
double a, b;
cin >> a >> b;
cout << max(a, b)<<endl;
cout << a;
return 0;
}
Now Supposing that a = 30.5 & b = 26.4.
The anticipated result is 30 however on one computer(MinGW & VS 2005) I get 30.5.
Does anyone have an interpretation for this ? It makes no sense to me.
Edit 1 :
on third line output is 30.5 instead of the anticipated 30
Solution
std::max() is shadowing it, but why it shadows it on one computer and it doesn't on another I didn't investigate in that.
So try to avoid naming your functions or classes with names reserved for the standard library.
This is whats resulting in the weird output:
using namespace std;
When calling max() you may be calling std::max() which may be included in <iostream> with no guarantees. Try this:
cout << ::max(a, b)<<endl; //forces global scope
Should print out 30.

Offsetof Function with std::vector

Could someone explain to me why the offsetof function does not work on std::vectors as shown below:
#include <windows.h>
#include <iostream>
#include <vector>
using namespace std;
struct FooStruct {
double x;
double y[10];
std::vector<double> z;
};
int main() {
cout << offsetof(FooStruct, x) << endl;
cout << offsetof(FooStruct, y[2]) << endl;
cout << offsetof(FooStruct, z[2]) << endl;
system("Pause");
}
Calling offsetof(FooStruct, z[2]) produces the following compiling error:
cannot apply 'offsetof' when 'operator[]' is overloaded
offsetof(FooStruct, z[2]) makes no sense. The elements of z are not contained within a FooStruct, they're accessed via the std::vector, which has at its core a pointer to some other allocation on the heap within which z[2] can be found.
In any case, the error (which seems confusing I understand) is probably popping up because std::vector overloads operator[], not because your class FooStruct overloads operator[] (which, assuming we see the whole definition, it doesn't).
If you want to find the offset of z[2] in relation to z[0], you could just compute the difference between &z[0] and &z[2] like this: std::cout << (&z[2] - &z[0]) << '\n';
Because offsetof isn't a function but a macro, and only works on POD types, or standard layout class in C++11. It's only there for backward compatibility with C.
The reason the compiler refuses to allow you to use the subscription operator, all issues aside, is because the macro is evaluated at compile time, but the overloaded operator might do some work at runtime to calculate the result.

C++ What's the usage difference between get and typecasting? Which one should I use?

#include <iosteam>
using namespace std;
Class A
{
int k;
public:
int getK() { return k; }
operator int() { return k; }
};
int main()
{
A a;
cout << a.getK() << " " << int(a) << endl;
}
What's the difference, and which one should I use? I'm wondering if typecasting returns a reference and getK returns a copy.
The only difference is that typecasting can be implicit.
int i = a;
Note that c++11 allow you to force cast operator to be explicitly called.
explicit operator int() { return k; }
They are both returning copies. Providing a cast operator usually is for when casting is necessary. For example you might do something like this maybe:
#include <iosteam>
using namespace std;
Class A
{
double k;
public:
A(double v) : k(v) {}
double getK() { return k; }
operator int() { return static_cast<int>(k); }
};
int main()
{
A a(3.14);
cout << a.getK() << " " << int(a) << endl; // 3.14 3
}
In general I avoid cast operators entirely because I prefer explicit casting.
It returns what the return type is. If you cast to a reference, then that's what you get back. What you're doing both times is making a copy.
The "difference" is what your method does. Your "cast" could add 5 to it and then return it. Or anything you want.
As for appropriateness, as chris said in the first comment, it's usually a "is your class a or not?" type question. Operators should be done for common conversions because your class operates as something, not merely to extract something from it. That's why it's a separate function to convert strings to integers, rather than being merely a cast on the string class. Whereas a complex number type can often be cast directly to a double or int, though that strips information from it. That the conversions can be "abused" is actually why some modern languages don't allow operator overloading. Others take the approach of while it can be abused, it can also be awesome. That's the C++ philosophy on most things: give all the tools, let the user do good or bad with them.
I hope that made sense.

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;

Can I define a type based on the result of some calculation?

I perform some calculations, based on the result, I would like to either use a short int or int for some type of data for the remaining program. Can (/How can) this be done sensibly in C or C++? I don't really care about the amount of memory used (i.e., 2 or 4 bytes), my primary aim is to access generic arrays as if they contained data of this type. I would like to avoid code such as the following:
char s[128];
if (result of preliminary calculations was A)
*((int*) s) = 50;
else
*((short int*) s) = 50;
to set the first 4 or 2 bytes of s. A conditional global typedef would be ideal:
if (result of preliminary calculations was A)
typedef int mytype;
else
typedef short int mytype;
I am not that familiar with C++ class templates (yet). Do they apply to my problem? Would I have to change the declarations throughout my program (to myclass< > and myclass< >*)?
Many thanks!
Frank
Edit: The values may not always be aligned. I.e, a int can start at position 21. Thanks for the answers.
For plain C, you could do this using function pointers:
static union { s_int[32]; s_short[64]; s_char[128]; } s;
static void set_s_int(int i, int n)
{
s.s_int[i] = n;
}
static int get_s_int(int i)
{
return s.s_int[i];
}
static void set_s_short(int i, int n)
{
s.s_short[i] = n;
}
static int get_s_short(int i)
{
return s.s_short[i];
}
static void (*set_s)(int, int);
static int (*get_s)(int);
Set them once based on the preliminary calculations:
if (result of preliminary calculations was A)
{
set_s = set_s_int;
get_s = get_s_int;
}
else
{
set_s = set_s_short;
get_s = get_s_short;
}
Then just use the function pointers in the rest of the program:
set_s(0, 50); /* Set entry 0 in array to 50 */
Your file writing function can directly reference s or s.s_char depending on how it works.
In C and C++, all type information is defined at Compile-time. So no, you cannot do this.
If the result of the preliminary calculations can be found at compile time, then this can work. Here are some simple examples to show how this can work. To do more complicated examples, see http://en.wikipedia.org/wiki/Template_metaprogramming
using namespace std;
#include <iostream>
template<int x> struct OddOrEven { typedef typename OddOrEven<x-2>::t t; };
template<> struct OddOrEven<0> { typedef short t; };
template<> struct OddOrEven<1> { typedef int t; };
template<bool makeMeAnInt> struct X { typedef short t; };
template<> struct X<true> { typedef int t; };
int main(void) {
cout << sizeof(X<false>::t) << endl;
cout << sizeof(X<true>::t) << endl;
cout << sizeof(OddOrEven<0>::t) << endl;
cout << sizeof(OddOrEven<1>::t) << endl;
cout << sizeof(OddOrEven<2>::t) << endl;
cout << sizeof(OddOrEven<3>::t) << endl;
cout << sizeof(OddOrEven<4>::t) << endl;
cout << sizeof(OddOrEven<5>::t) << endl;
}
I think above is standard C++, but if not I can tell you this work on g++ (Debian 4.3.2-1.1) 4.3.2
I think your main problem is how you plan to read the data from s later on if you don't know what type to read.
If you have that part covered, you can use a union:
union myintegers
{
int ints[32];
short shorts[64];
};
Now simply use the type you want.
myintegers s;
if (result of preliminary calculations was A)
s.ints[0] = 50;
else
s.shorts[0] = 50;
As a step further, you could wrap it all in a class which is constructed with result of preliminary calculations was A and overrides the operators * and [] to store in one or the other.
But are you sure you want any of that?
In current C++ standard (C++03), you can't.
In fact you can use some advanced metaprogramming tricks but it will not help most of the time.
In the next standard (C++0x, certainly C++11 in the end), you will be able to use the keyword decltype to get the type of an expression. If you're using VC10 (VS2010) or GCC 4.4 or more recent, then you already have the feature available.
You could abuse templates for this purpose. Any code that's subject to the decision would have to be templated based on the int type. One branch would instantiate the int version, the other would instantiate the short int version. This is probably a bad idea*.
Edit
*Well, it's only a bad idea to apply this to your overall architecture. If you have a particular data type that encapsulates the varied behavior, a template should work just fine.
Here's a variation on Aaron McDaid's answer to illustrate it's use with conditions:
#include <iostream>
#include <string>
using namespace std;
template<int x> struct OddOrEven { typedef typename OddOrEven<x-2>::t t; };
template<> struct OddOrEven<0> { typedef short t; };
template<> struct OddOrEven<1> { typedef int t; };
int main() {
cout << "int or short? ";
string which;
cin >> which;
if (which.compare("int") == 0)
cout << sizeof(OddOrEven<1>::t) << endl;
else if (which.compare("short") == 0)
cout << sizeof(OddOrEven<0>::t) << endl;
else
cout << "Please answer with either int or short next time." << endl;
return 0;
}
This is a code snippet from a project I had a while back.
void* m_pdata;
if (e_data_type == eU8C1){
pimage_data = new unsigned char[size_x * size_y];
}
if (e_data_type == eU16C1){
pimage_data = new unsigned short[size_x * size_y];
}
I hope it can help you
Since your stated goal is to store information efficiently on disk, you should learn to stop writing memory images of C/C++ data structures to disk directly and instead serialize your data. Then you can use any of a number of forms of variable-length coding ("vlc") to get the effect you want. The simplest is a coding with 7 bits per byte where the 8th bit is a continuation flag indicating that the value is continued in the next byte. So 259 would be stored as (binary, with continuation bit marked by spacing and byte boundaries marked by ;):
1 0000010 ; 0 0000011
Alternatively you could use the head nibble to signal the number of bytes that will follow, or use a scheme similar to UTF-8 with slightly more overhead but stricter resynchronization guarantees. There are also vlcs with are designed to be parsable and easily resynchronized when reading either forward or in reverse.