I'm not sure how I should word this, so I'll attempt to put it in code. (This has many errors I know it will not compile it is simply to show what I want to do because I can't put it in words)
using namespace std; //for correctness sake
class foo {
public:
foo(int a=0, int n=0);
void stuff(int a);
void function(int n);
const int get_function() {return n;}
const int get_stuff(){return a;}
private:
int n, a;
};
struct Store{
public: get_foo(){return vector<f.foo>;} //I'm not too sure of the syntax here but you get the idea
private:
foo f;
}
Basically I want to take all the information that is returned in class foo, and output this, formatted, to a file. Thing is, I need to make many of these within the file and it has to be able to read it back for it to be worth anything.
So just appending each consecutive foo class to the file won't work(at least I don't see how).
I tried using ostream to overload the << operator, but I'm not sure how to call it to write it to the file. Any suggestions are welcome! Thanks.
I think your Store should be like this:
struct Store
{
public:
std::vector<foo> get_foo()
{
return f;
}
private:
std::vector<foo> f;
};
To overload << of std::ostream:
std::ostream& operator<<(std::ostream& out, const Store& f)
{
for (auto &x : f.get_foo())
out << x.get_function() << ", " << x.get_stuff() << "\n";
return out;
}
//Without auto
std::ostream& operator<<(std::ostream& out, const Store& f)
{
std::vector<foo> q = f;
for (int i=0; i<q.size(); i++)
out << q[i].get_function() << ", " << q[i].get_stuff() << "\n";
return out;
}
There are many tings wrong with your code.
So many that it's clear that you never read any C++ book and are just experimenting with a compiler.
Don't do that. C++ is really the worst language in the world to approach that way for many independent reasons.
No matter how smart you are.
Actually being smart is sort of a problem in certain areas because many C++ rules are not the result of a coherent logical design, but of historical evolution and committee decisions. Not even Hari Seldon would be able to foresee correctly what a committee would decide, you cannot deduce history.
Just pick a good book and read it cover to cover. There is no other sensible way to learn C++.
About writing structs to a file the topic is normally called "serialization" and takes care of the slightly more general problem of converting live objects into a dead sequence of bytes (written to a file or sent over the network) and the inverse problem "deserialization" of converting the sequence of bytes back into live objects (on the same system, on another identical system or even on a different system).
There are many facets of this problem, for example if your concern is about portability between systems, speed, size of the byte sequence, ability to reload bytes sequences that were saved back when your classes were slightly different because you evolved the program (versioning).
The simplest thing you can do is just fwrite things to a file, but this is most often simply nonsense in C++ and is a terrible way for many reasons even when it's technically possible. For example you cannot directly fwrite an std::vector object and hope to read it back.
I think you need something like this:
template<typename T>
std::ostream& operator << (std::ostream& out, const std::vector<T*>& elements)
{
for (size_t i = 0; i < elements.size(); i++)
out << elements[i] << ", ";
return out << std::endl;
}
Related
I have built a little class Card overloading the << operator, essentially printing out Suit and value of the card.
The implementation details are not relevant for the question I want to ask here just assume the obvious. For Card I built a class CardDeck. Of course a CardDeck can run out of cards. That motivated me to this attempt:
std::optional<Card> CardDeck::drawCard() {
if (this->Cards.empty()) {
return std::nullopt;
}
else {
Card card = this->Cards.front();
this->Cards.pop_front();
return std::optional<Card>{card};
}
}
Now one can draw a card and dealing with the possibility of a empty deck is the responsibility of client code using CardDeck, yet it is verbose that the method will not always return a value. I like that solution.
Anyways a newbie to C++ I made the naive ansatz:
std::cout<< cardDeck.drawCard().value_or("Out of cards!");
This fails as the type of "Out of cards!" is char* but not Card.
My question: Is there a way to safe the elegant oneliner without checking and accessing the vaule / using the replacement in two seperate places?
The easiest way to deal with this in my opion is to add an overload for operator << for std::optional<Card>. In there you can handle the logic on what to print like
std::ostream& operator <<(std::ostream& os, const std::optional<Card>& card)
{
if (card == std::nullopt)
return os << "Out of cards!";
else
return os << *card;
}
and then you can just have
std::cout << cardDeck.drawCard();
You might write generic helper function a la std::visit for variant but for std::optional, something like:
template <typename T, typename F, typename FEmpty>
auto my_optional_visit(const std::optional<T>& o, F f, FEmpty fEmpty)
{
return o ? f(*o) : fEmpty();
}
and then:
my_optional_visit(cardDeck.drawCard(),
[](const Card&c){ std::cout << c; },
[](){ std::cout << "Out of Cards!" });
I would use a function (either namespace scoped or a static member of card) that takes a std::optional<Card> and return its textual representaion as a string. The relevant bits would be:
class Card {
...
std::string repr() const {
std::string cr;
// writes the textual representation of a card here
return cr;
}
static std::string repr(const std::optional<Card> &card) {
if (card.has_value()) {
return card.value().repr();
}
return "Out of cards!";
}
};
std::ostream& operator << (std ostream& out, const Card& card) {
out << card.repr();
}
You would then simply use:
std::cout << Card::repr(cardDeck.drawCard());
A C++ function can only have one return type. In your case you'd like the type of the result to be determined at runtime, where it could be different every time it's called. That just isn't possible.
If you need to do this often enough, I'd suggest just creating a small wrapper function.
std::string optionalCardToString(const std::optional<Card> & card,
const std::string & emptyString) {
return card ? card->to_string() : emptyString;
}
std::cout << optionalCardToString(cardDeck.drawCard(), "Out of Cards");
If performance is a concern, there's plenty you could do to make this more efficient to avoid making copies, but the general idea is there.
I should note that in a real world scenario, you are unlikely to draw a Card from the CarDeck and just pipe it to cout. You typically will want to do something else with the card as well, such as add it to a Hand or a Pile. This need to do something else sort of negates your concern about having to mention the value more than once.
Right, I'm not even sure how to correctly formulate this; I feel it's a bit of an involved question. I'm sure someone can help me out here though.
This is what I want to do:
Have a single class that I can send stuff to, like this.
icl << "Blah blah blah" << std::endl;
I want to be able to .attach() classes that inherit std::basic_ostream to it.
Those classes would then be able to format the output their own way. One might add a timestamp and write to a log, the other might write it to the console, the other might display it in-game.
Anyone care to get me started in the right direction? Here's the idea I pretty much have.
#include <vector>
class OutputMan {
std::vector<std::basic_ostream&> m_Streams;
public:
void attach(std::basic_ostream& os) {
m_Streams.push_back(os);
}
}
Question #1: What do I need to inherit and override to send
icl << "Blah!" << std::endl;
To every stream in m_Streams?
Question #2: How do I inherit std::basic_ostream and create a class that changes the output to, for example, add a timestamp to the start of it? I also want for this class to output to a file.
I think I'd do things a bit differently. I've probably made this just a bit more elaborate than necessary -- I'm afraid I may have gotten a little carried away with trying to put new C++11 features to good use. Anyway, on with the code:
#include <streambuf>
#include <fstream>
#include <vector>
#include <iostream>
#include <initializer_list>
namespace multi {
class buf: public std::streambuf {
std::vector<std::streambuf *> buffers;
public:
typedef std::char_traits<char> traits_type;
typedef traits_type::int_type int_type;
buf(std::vector<std::ofstream> &buf) {
for (std::ofstream &os : buf)
buffers.push_back(os.rdbuf());
}
void attach(std::streambuf *b) { buffers.push_back(b); }
int_type overflow(int_type c) {
bool eof = false;
for (std::streambuf *buf : buffers)
eof |= (buf -> sputc(c) == traits_type::eof());
return eof ? traits_type::eof() : c;
}
};
class stream : public std::ostream {
std::vector<std::ofstream> streams;
buf outputs;
public:
stream(std::initializer_list<std::string> names)
: streams(names.begin(), names.end()),
outputs(streams),
std::ostream(&outputs)
{ }
void attach(std::ostream &b) {
outputs.attach(b.rdbuf());
}
};
}
int main() {
multi::stream icl({"c:\\out1.txt", "c:\\out2.txt"});
icl.attach(std::cout);
icl << "Blah blah blah" << std::endl;
}
As you can see, this already accepts manipulators (which should work with any manipulator, not just std::endl). If you want to write to multiple files (things that could/can be opened as fstreams) you can specify as many of those names in the constructor as you like (within the limits imposed by your system, of course). For things like std::cout and std::cerr for which you don't necessarily have a file name, you can use attach as you originally intended.
I suppose I should add that I'm not entirely happy with this as-is. It'd take some fairly serious rewriting to do it, but after some thought, I think the "right" way would probably be for multi::stream's ctor to be a variadic template instead, so you'd be able to do something like: multi::stream icl("c:\\out1.txt", std::cout);, and it would sort out how to use each parameter based on its type. I may update this answer to include that capability some time soon.
As far as the second question goes, I've written another answer that covers the basic idea, but is probably a bit overly elaborate, so the part you care about may kind of get lost in the shuffle, so to speak -- it has quite a bit of logic to deal with line lengths that you don't really care about (but does produce each output line with a specified prefix, like you want).
You may need something like this:
class OutputMan {
std::vector<std::ostream*> m_Streams;
public:
void attach(std::ostream *os) {
m_Streams.push_back(os);
}
template <typename T>
OutputMan &operator<<(const T &t) {
for (int i=0; i<m_Streams.size(); i++)
*m_Streams[i] << t;
return *this;
}
};
int main() {
ofstream file("test.txt");
OutputMan x;
x.attach(&cout);
x.attach(&cerr);
x.attach(&file);
x << "Hello" << 123;
}
For simplicity I used std::ostream*. To accept stuffs by << I overloaded operator<<.
Note: If you want OutputMan accepts std::endl as well as other things, read here.
Is there a (more or less at least) standard int class for c++?
If not so, is it planned for say C++13 and if not so, is there any special reasons?
OOP design would benefit from it I guess, like for example it would be nice to have an assignment operator in a custom class that returns an int:
int i=myclass;
and not
int i=myclass.getInt();
OK, there are a lot of examples where it could be useful, why doesn't it exist (if it doesn't)?
It is for dead reckoning and other lag-compensating schemes and treating those values as 'normal' variables will be nice, hopefully anyway!.
it would be nice to have an assignment operator in a custom class that returns an int
You can do that with a conversion operator:
class myclass {
int i;
public:
myclass() : i(42) {}
// Allows implicit conversion to "int".
operator int() {return i;}
};
myclass m;
int i = m;
You should usually avoid this, as the extra implicit conversions can introduce ambiguities, or hide category errors that would otherwise be caught by the type system. In C++11, you can prevent implicit conversion by declaring the operator explicit; then the class can be used to initialise the target type, but won't be converted implicitly:
int i(m); // OK, explicit conversion
i = m; // Error, implicit conversion
If you want to allow your class to implicitly convert to int, you can use an implicit conversion operator (operator int()), but generally speaking implicit conversions cause more problems and debugging than they solve in ease of use.
If your class models an int, then the conversion operator solution presented by other answers is fine, I guess. However, what does your myclass model?
What does it mean to get an integer out of it?
That's what you should be thinking about, and then you should come to the conclusion that it's most likely meaningless to get an integer without any information what it represents.
Take std::vector<T>::size() as an example. It returns an integer. Should std::vector<T> be convertible to an integer for that reason? I don't think so. Should the method be called getInt()? Again, I don't think so. What do you expect from a method called getInt()? From the name alone, you learn nothing about what it returns. Also, it's not the only method that returns an integer, there's capacity() too.
Implement operator int () for your class
This can be realized by the cast operator. E.g:
class MyClass {
private:
int someint;
public:
operator const int() {
return this->someint;
}
}
No there isn't any standard int class. For things such as BigDecimal you can look at Is there a C++ equivalent to Java's BigDecimal?
As for int, if you really need it, you can create your own. I have never come across an instance where I needed an Integer class.
No, and there won't be any. What you want to do can be done with conversion operator:
#include <iostream>
struct foo {
int x;
foo(int x) : x(x) {}
operator int() { return x; }
};
int main() {
foo x(42);
int y(x);
std::cout << y;
}
No, and there probably won't be.
int i=myclass;
This is covered by conversion operators:
struct MyClass {
operator int() {
return v;
}
int v;
} myclass = {2};
int i = myclass; // i = 2
Not everything has to be 'object oriented'. C++ offers other options.
There are obvious reasons to have a class for int, because int by itself does not allow for the absence of any value. Take for instance a JSON message. It can contain the definition for an object named “foo”, and an integer named “bar”, for example:
{"foo": {"bar": 0}}
Which has the meaning that “bar" is equal to 0 (zero), but if you omit “bar”, like this:
{"foo": {}}
Now it takes on the meaning that “bar” is non-existent, which is a completely different meaning and cannot be represented by int alone. In the old days, if this situation arose, some programmers would use a separate flag, or use a specific integer value to signify that the value was not supplied, or undefined, or non-existent. But whatever you call it, a better way is to have a class for integer which defines the functionality and makes it reusable and consistent.
Another case would be a database table that has an integer column added some time after it’s creation. Records that were added prior to when the new column was added will return null, meaning no value present, and records added after the column’s creation would return a value. You may need to take a different action for null value vs. 0 (zero).
So here's the beginnings of what a class for int or string might look like. But before we get to the code, let's look at the usage as that is why you would create the class in the first place, to make your life easier in the long run.
int main(int argc, char **argv) {
xString name;
xInt age;
std::cout<< "before assignment:" << std::endl;
std::cout<< "name is " << name << std::endl;
std::cout<< "age is " << age << std::endl;
// some data collection/transfer occurs
age = 32;
name = "john";
// data validation
if (name.isNull()) {
throw std::runtime_error("name was not supplied");
}
if (age.isNull()) {
throw std::runtime_error("age was not supplied");
}
// data output
std::cout<< std::endl;
std::cout<< "after assignment:" << std::endl;
std::cout<< "name is " << name << std::endl;
std::cout<< "age is " << age << std::endl;
return 0;
}
Here is the sample output from the program:
before assignment:
name is null
age is null
after assignment:
name is john
age is 32
Note that when the instance of the xInt class has not been assigned a value, the << operator automatically prints "null" instead of zero, and the same applies to xString for name. What you do here is totally up to you. For instance, you might decide to print nothing instead of printing “null”. Also, for the sake of brevity, I've hard coded the assignments. In the real world, you would be gathering/parsing data from a file or client connection, where that process would either set (or not set) the data values according to what is found in the input data. And of course, this program won't actually ever throw the runtime exceptions, but I put them there to give you a flavor of how you might throw the errors. So, one might say, well, why don't you just throw the exception in your data collection process? Well, the answer to that is, with the eXtended class variables (xInt & xString), we can write a generic, reusable, data gathering process and then just examine the data that is returned in our business logic where we can then throw appropriate errors based on what we find.
Ok, so here's the class code to go with the above main method:
#include <iostream>
#include <string>
class xInt {
private:
int _value=0;
bool _isNull=true;
public:
xInt(){}
xInt(int value) {
_value=value;
_isNull=false;
}
bool isNull(){return _isNull;}
int value() {return _value;}
void unset() {
_value=0;
_isNull=true;
}
friend std::ostream& operator<<(std::ostream& os, const xInt& i) {
if (i._isNull) {
os << "null";
} else {
os << i._value;
}
return os;
}
xInt& operator=(int value) {
_value=value;
_isNull=false;
return *this;
}
operator const int() {
return _value;
}
};
class xString {
private:
std::string _value;
bool _isNull=true;
public:
xString(){}
xString(int value) {
_value=value;
_isNull=false;
}
bool isNull() {return _isNull;}
std::string value() {return _value;}
void unset() {
_value.clear();
_isNull=true;
}
friend std::ostream& operator<<(std::ostream& os, const xString& str) {
if (str._isNull) {
os << "null";
} else {
os << str._value;
}
return os;
}
xString& operator<<(std::ostream& os) {
os << _value;
return *this;
}
xString& operator=(std::string value) {
_value.assign(value);
_isNull=false;
return *this;
}
operator const std::string() {
return _value;
}
};
Some might say, wow, that's pretty ugly compared to just saying int or string, and yes, I agree that it's pretty wordy, but remember, you only write the base class once, and then from then on, your code that you're reading and writing every day would look more like the main method that we first looked at, and that is very concise and to the point, agreed? Next you'll want to learn how to build shared libraries so you can put all these generic classes and functionality into a re-usable .dll or .so so that you're only compiling the business logic, not the entire universe. :)
There's no reason to have one, and so there won't be any.
Your cast operator should realize this
An example
class MyClass {
private:
int someint;
public:
operator const int() {
return this->someint;
}
}
Edit:
So this question was misinterpreted to such a ludicrous degree that it has no point anymore. I don't know how, since the question that I actually asked was whether my specific implementation of this—yes, known to be pointless, yes, not remotely resembling idiomatic C++—macro was as good as it could be, and whether it necessarily had to use auto, or if there was a suitable workaround instead. It was not supposed to generate this much attention, and certainly not a misunderstanding of this magnitude. It's pointless to ask respondents to edit their answers, I don't want anybody to lose reputation over this, and there's some good information floating around in here for potential future viewers, so I'm going to arbitrarily pick one of the lower-voted answers to evenly distribute the reputation involved. Move along, nothing to see here.
I saw this question and decided it might be fun to write a with statement in C++. The auto keyword makes this really easy, but is there a better way to do it, perhaps without using auto? I've elided certain bits of the code for brevity.
template<class T>
struct with_helper {
with_helper(T& v) : value(v), alive(true) {}
T* operator->() { return &value; }
T& operator*() { return value; }
T& value;
bool alive;
};
template<class T> struct with_helper<const T> { ... };
template<class T> with_helper<T> make_with_helper(T& value) { ... }
template<class T> with_helper<const T> make_with_helper(const T& value) { ... }
#define with(value) \
for (auto o = make_with_helper(value); o.alive; o.alive = false)
Here's an (updated) usage example with a more typical case that shows the use of with as it is found in other languages.
int main(int argc, char** argv) {
Object object;
with (object) {
o->member = 0;
o->method(1);
o->method(2);
o->method(3);
}
with (object.get_property("foo").perform_task(1, 2, 3).result()) {
std::cout
<< (*o)[0] << '\n'
<< (*o)[1] << '\n'
<< (*o)[2] << '\n';
}
return 0;
}
I chose o because it's an uncommon identifier, and its form gives the impression of a "generic thing". If you've got an idea for a better identifier or a more usable syntax altogether, then please do suggest it.
If you use auto, why use macros at all?
int main()
{
std::vector<int> vector_with_uncommonly_long_identifier;
{
auto& o = vector_with_uncommonly_long_identifier;
o.push_back(1);
o.push_back(2);
o.push_back(3);
}
const std::vector<int> constant_duplicate_of_vector_with_uncommonly_long_identifier
(vector_with_uncommonly_long_identifier);
{
const auto& o = constant_duplicate_of_vector_with_uncommonly_long_identifier;
std::cout
<< o[0] << '\n'
<< o[1] << '\n'
<< o[2] << '\n';
}
{
auto o = constant_duplicate_of_vector_with_uncommonly_long_identifier.size();
std::cout << o <<'\n';
}
}
EDIT: Without auto, just use typedef and references.
int main()
{
typedef std::vector<int> Vec;
Vec vector_with_uncommonly_long_identifier;
{
Vec& o = vector_with_uncommonly_long_identifier;
o.push_back(1);
o.push_back(2);
o.push_back(3);
}
}
?? attempted vb syntax into C++
with says do all the things in the following block by default referencing the object I've said to do it with right? Executes a series of statements making repeated reference to a single object or structure.
with(a)
.do
.domore
.doitall
so how is the example giving you the same syntax?
to me examples of why to use a with where multiple de referencess
so rather than
book.sheet.table.col(a).row(2).setColour
book.sheet.table.col(a).row(2).setFont
book.sheet.table.col(a).row(2).setText
book.sheet.table.col(a).row(2).setBorder
you have
with( book.sheet.table.col(a).row(2) )
.setColour
.setFont
.setText
.setBorder
seems just as easy, and more common syntax in C++ to
cell& c = book.sheet.table.col(a).row(2);
c.setColour
c.setFont
c.setText
c.setBorder
For C++0x (which you're assuming):
int main() {
std::vector<int> vector_with_uncommonly_long_identifier;
{
auto& o = vector_with_uncommonly_long_identifier;
o.push_back(1);
o.push_back(2);
o.push_back(3);
}
}
Why not just use a good lambda?
auto func = [&](std::vector<int>& o) {
};
func(vector_with_a_truly_ridiculously_long_identifier);
The simple fact is that if your identifiers are so long, that you can't type them out every time, use a reference, function, pointer, etc to solve this problem, or better, refactor the name. Statements like this (e.g. using() in C#) have additional side effects (deterministic cleanup, in my example). Your statement in C++ has no notable actual benefits, since it doesn't actually invoke any additional behaviour against just writing the code out.
I am trying to figure out the memory consumption by my (C++) program using gprof. The program does not have a gui, it is entirely cli based.
Now, I am new to gprof, so I read a few tutorials, that taught me how to run gprof and spot time consumption.
However, I need to find out the memory consumption by a specific set of classes.
Say there is a program with many types, A, ..., Z. Now I want to run my program and see how many accumulated memory was used by objects of the classes A, E, I, O, U (for example).
Have you guys any ideas or pointers how I could approach this task?
I am not exclusively considering gprof, I am open for any (fos) software that gets the job done.
I have, of course, searched both google and stackoverflow.com for any answer to this problem, but either I use the wrong keywords or there is nobody having this problem out there.
Edit: Suggestions about doing this manually are obvious. Of course I could code it into the application, but its about a great deal of classes I would rather not change. Also, I want to have the total memory consumption, so I cannot only count all created objects, because I would have to track the size of the object individually.
Edit2: I went with a modification of DeadMG's suggestion, which I only have to inherit from. It works pretty well, so, if anybody has as similar problem, try this.
class GlobalObjectCounter {
public:
struct ClassInfo {
unsigned long created;
unsigned long destroyed;
unsigned short size;
ClassInfo() : created(0), destroyed(0), size(0) {}
ClassInfo(unsigned short _size) : created(0), destroyed(0), size(_size) {}
void fmt(std::ostream& os) {
os << "total: " << (this->created) << " obj = " << (this->created*this->size) << "B; ";
os << "current: " << (this->created-this->destroyed) << " obj = " << ((this->created-this->destroyed) * this->size) << "B; ";
}
};
protected:
static std::map<std::string,ClassInfo> classes;
GlobalObjectCounter() {}
public:
static void dump(std::ostream& os) {
for (std::map<std::string,ClassInfo>::iterator i = classes.begin(); i != classes.end(); ++i) {
os << i->first << ": ";
i->second.fmt(os);
os << "\n";
}
}
};
template <class T> class ObjectCounter : public GlobalObjectCounter {
private:
static ClassInfo& classInfo() {
static ClassInfo& classInfo = classes[std::string("") + typeid(T).name()];
classInfo.size = sizeof(T);
return classInfo;
}
public:
ObjectCounter() {
classInfo().created++;
}
ObjectCounter(ObjectCounter const& oc) {
classInfo().created++;
}
ObjectCounter& operator=(const ObjectCounter&) {}
~ObjectCounter() {
classInfo().destroyed++;
}
};
The map lookup is a bit nasty, I admit it, but I didn't have the nerve to take care of storing the iterator for each class. The main issue was that you would have to explicitly initialise it for each counted class. If you know how to do that better, tell me how.
I'm not aware of gprof even attempting to deal with questions of memory usage. The obvious alternative would be valgrind. If you only care about total memory usage, you could also do the job on your own (overload ::operator new and ::operator delete to track how much memory the program has requested). Of course, it's possible that you have some code that obtains memory by other means (e.g., directly calling something like sbrk), but that's fairly unusual. Those don't attempt to track statically allocated and/or stack usage though.
Trivial.
template<typename T> class Counter {
static int count = 0;
Counter() { count++; }
Counter(const Counter&) { count++; }
Counter& operator=(const Counter&) {}
~Counter() { count--; }
};
class A : Counter<A> {
static int GetConsumedBytes() {
return sizeof(A) * count;
}
};
If the use of A involves dynamic memory, then this solution can be improved on. You can also override the global operator new/delete.
GlibC provides statistics on heap memory allocation. Take a look at mallinfo. You could probably obtain statistics at various points during execution and get some kind of idea of how much memory is being used.