How can I (cleanly!) subclass std::stringstream for a customization? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a logging class with a std::stringstream member. I use it's output << overloading to get a nice easy means for catching all the data types std::stringstream gives me for free.
Here's the problem. After sending data into the stream, I want an easy way to flush it automatically to my destination (which is variable/dynamic in nature).
std::ostream will "auto flush" if you send an endl down it. That's and acceptable solution I would duplicate.
How can I implement that myself? Note that I don't want to override every operator<<() overload in std::stringstream!

I've done a similar thing. What I do is use an unnamed class instance to consume the output and put the flushing in the destructor. Something like this:
int i = 0;
MyClass() << "This is a log message containing an int: " << i;
// here, the class destructs and does whatever you need to do to flush the stream

Instead of subclassing std::stringstream, it's prefered to use composition (see Composition over inheritance).
With this, your class would look like this:
class Log{
std::stringstream _stream;
[...] // Constructor and other class logic
public:
Log& operator<<(string s){
_stream << s << endl;
return *this;
}
};

Related

C++ single-function variable placement [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm writing a class that reads data from a file. The project is still in development, and it's likely that I'll change the file name or path later on, so I've stored it in a std::string for quicker editing.
Given that the file name is going to be used several times in a function, but is only going to be used in one function, is there a canonical cpp rule about where I should define the variable?
//don't know where I'll define this
std::string file_name = "path/to/file.foo";
//a.h file
class A {
public:
void fileFunc();
private:
//do i define it here?
};
//a.cpp file
A::fileFunc() {
//or do i define it here?
std::ifstream in(file_name);
if(in) {
//do things
}
else {
std::cerr << "couldn't open " << file_name;
}
}
Keeps all information close to thiers use.
It will help the readability and the performance. See: https://en.wikipedia.org/wiki/Locality_of_reference
So
A::fileFunc() {
const std::string file_name = "path/to/file.foo"; // pls use const when you can
...
or
A::fileFunc(const std::string& file_name) {
...
BTW, I think this should be on https://codereview.stackexchange.com/, not stackoverflow.

C++ serializing an object containing an array of other objects [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have the object listed below.
class Customer
{
private:
std::string customerName;
std::string customerLastName;
std::string customerIdentityNumber;
std::vector<std::unique_ptr<Account>> customerAccounts;
}
How would one go about serializing this object? I've tried finding examples but these are all using some complex libraries. Surely there must be an easier way?
Coming from Java this is new to me.
I really recommend a serialization library such as boost::serialization
Its a great library, easy to use, extremely fast, and has much more than just this!
It's exactly what you're looking for.
I prefer a very simple and basic implementation. Lets assume that Serialize() function has already been implemented for Account class.
The implementation of Serialize() function of Customer class can be:
void Customer::Serialize(Archive& stream)
{
if(stream.isStoring()) //write to file
{
stream << customerName;
stream << customerLastName;
stream << customerIdentityNumber;
stream << customerAccounts.size(); //Serialize the count of objects
//Iterate through all objects and serialize those
std::vector<std::unique_ptr<Account>>::iterator iterAccounts, endAccounts;
endAccounts = customerAccounts.end() ;
for(iterAccounts = customerAccounts.begin() ; iterAccounts!= endAccounts; ++iterAccounts)
{
(*iterAccounts)->Serialzie(stream);
}
}
else //Reading from file
{
stream >> customerName;
stream >> customerLastName;
stream >> customerIdentityNumber;
int nNumberOfAccounts = 0;
stream >> nNumberOfAccounts;
customerAccounts.empty(); //Empty the list
for(int i=0; i<nNumberOfAccounts; i++)
{
Account* pAccount = new Account();
pAccount->Serialize(stream);
//Add to vector
customerAccounts.push_back(pAccount);
}
}
}
The code is self-explanatory. But idea is to archive count and then every element. This help while deserializing from file.

Am I able to complement a virtual function of subclasses? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i have a question. Lets say i have this virtual function in main class:
virtual void h_w() { cout << "Hello, wolrd!" << endl; }
And Im doing with the same function that:
void h_w() { cout << "Today is: " << math.rand(); << endl; }
Am I allowed to do that? I mean, can i change body of main function like I want in subclasses? Thanks.
Assuming you mean you want something like this:
class base {
public:
virtual void h_w() { std::cout << "Hello world!\n"; }
};
class derived : public base {
public:
void h_w() { std::cout << "Today is: " << rand() << "\n"; }
};
int main() {
std::unique_ptr<base> b = std::make_unique<derived>();
b->h_w();
}
...then yes, C++ supports that. In fact, this is pretty much a canonical demonstration of virtual functions, at least if you change names to (for example) "animal" as the base class and "duck" as the derived class, and have them print out something like "generic animal" and "duck" respectively. For the record, it's probably worth noting that most example based on animals are more or less broken in various ways, such as animals simply not following simple sets of rules like we expect code to.
A better example, would be something like a base class defining a generic interface to a database that allows things like reading a record, writing a record, and finding a set of records that satisfy some criteria. The derived class could then (for example) provide an implementation to carry out those "commands" in terms of some specific type of database--perhaps SQL, or perhaps some simple key/value storage engine, but the client doesn't know or care, beyond minor details like performance.
As to why this is better: first of all, because it corresponds much more closely to things you're likely to really do with a computer. Second, because we can define databases to really follow our rules and fulfill the obligations we set. With animals, we're stuck with all sorts of exceptions to any meaningful rule we might try to make, as well as the simple fact that (of course) being able to make a Duck say "quack" and a dog say "bow wow" isn't really very useful (and in the rare case that it is useful, we probably just want to save/retrieve its sound as some sort of blob, not define an entire new type to encode something better stored as data).

c++ using scope resolution operator in function call parameter [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Can someone please point me to an explanation what e.g. QIODevice::WriteOnly actually does?
full line of code:
file.open(stderr, QIODevice::WriteOnly);
from that link
thanks
According to the documentation for the QIODevice class, WriteOnly is as enum constant with value 2. It indicates that the device is open for writing.
I believe that the following example for enum hack will be useful to you.
class MyClass1 {
public:
enum { SIZE=10 };
};
class MyClass2 {
public:
enum { SIZE=20 };
};
int main() {
cout << MyClass1::SIZE << "\t" << MyClass2::SIZE << endl;
}
QIODevice::WriteOnly is just a flag, you're saying that you want to open the file only for writing.
If you would want only to read the file, QIODevice::ReadOnly would be the necessary flag to use.
And to read and write use flag: QIODevice::ReadWrite:
file.open(stderr, QIODevice::ReadWrite);

How to choose among two classes given a condition in c++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Suppose there are two classes Class1 and Class2. given a condition I have to choose among them in shortest way possible without using if-else.
Means least lines of code.
At compile time only!!!
class class1{};
class class2{};
auto data = (((condition) ? class1 : class2) *)(variable)
Assuming you need to create object at compile time depending on a variable, you can try something like following
class class1{};
class class2{};
int main( int argc, char *argv[] )
{
constexpr bool variable =true;
/* x is object of type class1 or class2 depending on
compile time constant 'variable'
*/
typedef std::conditional<variable, class1, class2>::type x;
//std::cout << typeid(x).name() << '\n';
return 0;
}
See Here