Conditional output - c++

I'd like to create a C++ ostream object that only outputs anything if a condition holds true, to use for debugging. What would be the easiest way to do this? I know that boost has classes that make this easy, but I'd like to know if there's a simple way to do it without boost. The documentation makes it seem like subclassing ostream::sentry would make this possible, but I can't find any source saying that's something that you can/should do.

Don't subclass, it's easier to use a wrapper:
class MaybeOstream
{
public:
MaybeOstream(std::ostream& stream_) : stream(stream_), bOutput(true) {}
void enable(bool bEnable) { bOutput = bEnable; }
template<typename T>
MaybeOstream& operator<< (T x)
{
if(bOutput)
stream << x;
return *this;
}
// Add other wrappers around ostream: operator void*, good(), fail(),
// eof(), etc., which just call through to the ostream
private:
std::ostream& stream;
bool bOutput;
}

Take a look at this paper on filtered streambufs.

Related

Should I use a class with static members to implement Template Method Pattern if I don't need to take care of internal function state?

The question is a bit confusing so let me clarify by explaining my predicament.
I'm using nlohman::json and trying to do conversions between nlohman::json value types and QStrings from QT 5.8. In order to do those conversions I came to the conclusion that I would need to use the json libraries json::is_typexxx for json value types. This ended up looking like this:
QString convertQString(const json &json_in) {
if (json_in.is_number_integer()) {
return //QString integer conversion
} else if (json_in.is_number_float()) {
return //QString float conversion
} else if (json_in.is_string()) {
return //QString std::string conversion
} else if (json_in.is_boolean()) {
return //QString bool conversion
}
return // QString no type found default
}
I soon realized that I would need to convert QStrings back into values for nlohman::json, in doing so I started to write the following function
void convertJson(.../**notimportant**/... json& json_out){
... /**more stuff here**/
if (json_out.is_number_integer()) {
...
} else if (json_out.is_number_float()) {
...
} else if (json_out.is_string()) {
...
} else if (json_out.is_boolean()) {
...
}
...
}
and soon realized I was just writing the same logic for checking types. Naturally I thought this was an excellent oportunity to use the Template Method Pattern, and started writing the following classes:
template<typename T>
class JsonChoice {
protected:
T makechoice(const nlohmann::json &json_in);
virtual T ifinteger() = 0;
...// other functions that follow the "iftypexxx()" convention
};
template<typename T>
T JsonChoice::choice(const nlohmann::json &json_in) {
if (json_in.is_number_integer()) {
return ifinteger();
... //you get the pattern...
}
QStringConverter : public JsonChoice<QString>{
...
protected:
QString ifinteger();
... //etc
};
// friend define operator ()?
JsonConverter : public JsonChoice<nlohmann::json>{
...
protected:
nlohmann::json ifinteger();
... //etc
};
// friend define operator ()?
It was at this point that I realized I didn't need state in either of my Template Method Pattern functors. However most examples I've seen of this pattern implemented are made like so:
TMPFunctor = tmpfun(statevar);
...
So I was wary of not following convention here, but since I didn't need any state, it didn't seem like it was a good idea to force myself to have to create a variable every time I wanted to use what was essentially a function with internal logic switched out depending on the signature. I started wondering if I even should use functors to accomplish this task, as I could techinically template every part of the process to simply create one function as well. Is this an adequate solution to this problem, to create a functor class with all static members, use it as a functor?
According to this statically overloading () is a problem however and I'm not sure if I should just wrap another class function in another function like so to solve this issue:
QString convertQstring(const nlohmann::json &json_in){
return QStringConverter.makechoice(json_in);
}
or just template every part of the function (which sounds annoying and ugly to me) to generalize the choice switch ie:
template<typename returnval, typename integerfunctemplate, ...>
returnval convert( const nlohmann::json &json_in){
if (json_in.is_number_integer()) {
return integerfunctemplate();
...
}

Extend boost property tree get for own types

How do I extend boost property tree to support my own types?
e.g. I want to write
boost::property_tree::basic_ptree<std::string,std::string> xml;
...
xml.get<int>("level"),
xml.get<double>("accuracy"),
xml.get<Ship>("sauce_pan"),
...
And then I guess somewhere I'd like to describe how to get a Ship from a boost::property_tree::basic_ptree<std::string,std::string> or something similar.
You need to provide a default constructor for Ship and a stream input operator:
struct Ship {
friend std::istream& operator>>(std::istream& s, Ship& e) {
/* read ship data from s */
return s;
}
};
Unfortunately, I'm not sure if this is an official feature of property_tree as I can not find it in the documentation.
For more fine-grained access get also takes a Translator as it's second argument.
struct ShipTranslatorJSON {
// the type we return
typedef Ship external_type;
// the type expect as an argument
typedef std::string internal_type;
boost::optional< external_type > get_value(const internal_type&) {
return external_type();
}
// only required when you actually use put
// boost::optional< T > put_value(const T &);
};
// use as
xml.get<Ship>("sauce_pan", ShipTranslatorJSON());
This method also seems more "official", although nothing in the documentation actually explains what a Translator really is.

Is it possible to overload operator<< like this? [duplicate]

This question already has answers here:
How to define a static operator<<?
(4 answers)
Closed 9 years ago.
Let's say I have a class called "Logger". The name is self explanatory, it logs stuff. I have a static method, which logs stuff (Logger::log(string msg)).
I wanted to overload the operator <<, so that I could do something like:
Logger << "AW YEAH, I LOVE C++";
I tried to do this, but couldn't. What I managed, was this:
Logger l;
l << ":(";
...
is it possible what I want to do? And if yes, how?
Thank You in advance :)
If Logger is the name of a class then of course you can't do that. Use something like
Logger &log() {
static Logger l;
return l;
}
log() << "And the answer is" << 42;
Assuming you want to leverage the output operators provide by std::ostream you should not try to overload the output operator! Instead, you'd create a suitable stream buffer (i.e., a class derived from std::streambuf) and implement your custom output logic in that class's overflow() and sync() methods. Your logger would then derive from std::ostream and initialize its base class to use your custom stream buffer.
Overloaded operators operate on values, not on types.
Maybe you should rename your class, and then create a suitable global object. For example:
logger.h:
class mylogger { /* ... */ };
extern mylogger logger;
logger.cpp:
#include "logger.h"
mylogger logger;
Usage:
#include "logger.h"
logger << "Done";
Beware of global initialization issues; though; check out your implementation of std::cout for a way to solve this (e.g. with a Schwartz counter).
It is possible, but you need to figure out what interface you really want. One option is to make your Logger be an std::ostream (inheritance) and then things would kind of work out of the box. The alternative is to maintain a logger that is unrelated (no inheritance) to std::ostream, but then you need to provide Logger& operator<<(Logger&,T const &) for any and all types T you want to log. For the particular case of std::string you could do:
Logger& operator<<(Logger& logger, std::string const& msg) {
logger.log(msg); // need not be, and problably should be static
return logger;
}
Making this generic involves as with most generic code in C++ the use of templates:
template <typename T>
Logger& operator<<(Logger& logger, T const & obj) {
// do specific work based on the type, or a completely generic approach:
std::ostringstream st;
st << obj;
logger.log(st.str());
return logger;
}
At this point you might want to consider adding support for manipulators and... well, if you start down this path, it might make more sense not to create the std::ostringstream in each function, but create a single one as a member, then dump all data into that stream and use some manipulator to extract the string and write it (for example on std::flush or std::ends...)
template <typename T>
Logger& operator<<(Logger& logger, T const& obj) {
logger.stream << obj;
return logger;
}
Logger& operator<<(Logger& logger, std::ostream& (*manip)(std::ostream&)) {
logger.stream << manip;
if (manip == static_cast<std::ostream& (*)(std::ostream&)>(std::flush)) {
logger.write(); // flush to disk
}
return logger;
}
// add support for other manipulators...
Then again you might start wondering if it would not be easier to pull some off the shelf logging library and just use it.

Secure direct access to class members

I wonder if the following syntax can be "admitted" or if good practices consider this as coming from hell. The goal would be to add a level of protection to force the developer to be well-conscious of what he is doing. Here is the syntax :
class MyClass
{
public:
template<bool RemoveProtection = false>
inline std::ofstream& writeStream()
{
static_assert(RemoveProtection, "You're doing it wrong");
return _writeStream;
}
inline const std::ofstream& writeStream() const
{
return _writeStream;
}
protected:
std::ofstream _writeStream;
};
The use would be :
x.writeStream().good(); // <- OK
x.writeStream().put('c'); // <- NOT OK
x.writeStream<true>().put('c'); // <- OK
I find this as a convenient way to tell to the developer : "Beware, you are using a low-level function and you have to be careful with what you are doing". Is it a "acceptable" way of providing a direct access to class members with a kind of "protection" ? Is there other way of coding a such thing ?
Have a look at meagar's comment:
You're making your code ugly, harder to maintain and inconvenient for... what exactly? Define your interface. That is the interface to your class. Do not allow developers to bypass it by using some ridiculous template flag hackery. If you're writing code, you always have to know what you're doing. Having to explicitly type <true> to indicate you especially know what you're doing is just... very, very wrong-headed. Developers have documentation. They don't need training wheels and artificial restrictions, they need clear concise code that lets them get things done. – meagar 2012-10-06 02:41:53Z
A class you provide to others should never be able to get into an unpredicted state when another user uses it. An unpredicted state is in this case a state which you never considered when you were writing the class. As such you should either never allow access to low-level methods of your class or document possible flaws.
Lets say you're writing a logger:
struct MyLogger{
MyLogger(std::string filename) : stream(filename.c_str()){}
template <typename T>
MyLogger& operator<<(const T& v){ stream << v << " "; return *this;}
private:
std::ofstream stream;
};
Ignore that there isn't a copy constructor and that the assignment operand is missing. Also ignore that it's a crude logger, it doesn't even provide a timestamp. However, as you can see, the state of the logger depends completely on the logger's methods, e.g. if the file has been successfully opened it won't be closed until the logger gets destroyed.
Now say that we use your approach:
struct MyLogger{
MyLogger(std::string filename) : stream(filename.c_str()){}
template <typename T>
MyLogger& operator<<(const T& v){ stream << v << " "; return *this;}
template<bool RemoveProtection = false>
inline std::ofstream& writeStream()
{
static_assert(RemoveProtection, "You're doing it wrong");
return stream;
}
inline const std::ofstream& writeStream() const
{
return stream;
}
private:
std::ofstream stream;
};
And now someone uses the following code
logger.writeStream<true>.close();
Bang. Your logger is broken. Of course it's the users fault, since they used <true>, didn't they? But more often than not a user is going to copy example code, especially if he uses a library for the first time. The user sees your example
logger.writeStream().good(); // <- OK
logger.writeStream().put('c'); // <- NOT OK
logger.writeStream<true>().put('c'); // <- OK
and ignores the documentation completely at first. Then he's going to use the first and the last version. Later he discovers that the last version works every time! What a miraculous thing <true> is. And then he starts to blame you for evil things that happen, so you have protect yourself from blatant flames with a documentation which includes a warning:
/**
* \brief Returns a reference to the internal write stream
*
* \note You have to use the template parameter `<true>` in order to use it
*
* \warning Please note that this will return a reference to the internal
* write stream. As such you shouldn't create any state in which
* the logger cannot work, such as closing the stream.
*/
template<bool RemoveProtection = false>
inline std::ofstream& writeStream()
{
static_assert(RemoveProtection, "You're doing it wrong");
return stream;
}
So, what did we get? We still had to put that warning somewhere. It would have been much simpler if we made stream public:
struct MyLogger{
MyLogger(std::string filename) : stream(filename.c_str()){}
template <typename T>
MyLogger& operator<<(const T& v){ stream << v << " "; return *this;}
/**
* The internal write stream. Please look out that you don't create
* any state in which the logger cannot work, such as closing the stream.
*/
std::ofstream stream;
};
or sticked to
/** >put warning here< */
inline std::ofstream & writeStream()
{
return stream;
}
Woops. So either don't allow access to your low-level methods (build a wrapper to specific std::ofstream methods if they should be allowed to use them) or document the possible flaws which can happen if you alter the object's internals to much, but don't go the middle-way and make it look okay with a static_assert.

"Forward-unbreakable" accessor class templates [C++]

Unless I am thoroughly mistaken, the getter/setter pattern is a common pattern used for two things:
To make a private variable so that it can be used, but never modified, by only providing a getVariable method (or, more rarely, only modifiable, by only providing a setVariable method).
To make sure that, in the future, if you happen to have a problem to which a good solution would be simply to treat the variable before it goes in and/or out of the class, you can treat the variable by using an actual implementation on the getter and setter methods instead of simply returning or setting the values. That way, the change doesn't propagate to the rest of the code.
Question #1: Am I missing any use of accessors or are any of my assumptions incorrect? I'm not sure if I am correct on those.
Question #2: Are there any sort of template goodness that can keep me from having to write the accessors for my member variables? I didn't find any.
Question #3: Would the following class template be a good way of implementing a getter without having to actually write the accesor?
template <class T>
struct TemplateParameterIndirection // This hack works for MinGW's GCC 4.4.1, dunno others
{
typedef T Type;
};
template <typename T,class Owner>
class Getter
{
public:
friend class TemplateParameterIndirection<Owner>::Type; // Befriends template parameter
template <typename ... Args>
Getter(Args args) : value(args ...) {} // Uses C++0x
T get() { return value; }
protected:
T value;
};
class Window
{
public:
Getter<uint32_t,Window> width;
Getter<uint32_t,Window> height;
void resize(uint32_t width,uint32_t height)
{
// do actual window resizing logic
width.value = width; // access permitted: Getter befriends Window
height.value = height; // same here
}
};
void someExternalFunction()
{
Window win;
win.resize(640,480); // Ok: public method
// This works: Getter::get() is public
std::cout << "Current window size: " << win.width.get() << 'x' << win.height.get() << ".\n";
// This doesn't work: Getter::value is private
win.width.value = 640;
win.height.value = 480;
}
It looks fair to me, and I could even reimplement the get logic by using some other partial template specialization trickery. The same can be applied to some sort of Setter or even GetterSetter class templates.
What are your thoughts?
Whilst the solution is neat from implementation point of view, architectually, it's only halfway there. The point of the Getter/Setter pattern is to give the clas control over it's data and to decrease coupling (i.e. other class knowing how data is stored). This solution achieves the former but not quite the latter.
In fact the other class now has to know two things - the name of the variable and the method on the getter (i.e. .get()) instead of one - e.g. getWidth(). This causes increased coupling.
Having said all that, this is splitting proverbial architectural hairs. It doesn't matter all that much at the end of the day.
EDIT OK, now for shits and giggles, here is a version of the getter using operators, so you don't have to do .value or .get()
template <class T>
struct TemplateParameterIndirection // This hack works for MinGW's GCC 4.4.1, dunno others
{
typedef T Type;
};
template <typename T,class Owner>
class Getter
{
public:
friend TemplateParameterIndirection<Owner>::Type; // Befriends template parameter
operator T()
{
return value;
}
protected:
T value;
T& operator=( T other )
{
value = other;
return value;
}
};
class Window
{
public:
Getter<int,Window> _width;
Getter<int,Window> _height;
void resize(int width,int height)
{
// do actual window resizing logic
_width = width; //using the operator
_height = height; //using the operator
}
};
void someExternalFunction()
{
Window win;
win.resize(640,480); // Ok: public method
int w2 = win._width; //using the operator
//win._height = 480; //KABOOM
}
EDIT Fixed hardcoded assignment operator. This should work reasonably well if the type itself has an assignment operator. By default structs have those so for simple ones it should work out of the box.
For more complex classes you will need to implement an assignment operator which is fair enough. With RVO and Copy On Write optimizations, this should be reasonably efficient at run time.
FWIW here are my opinions on your questions:
Typically the point is that there is business logic or other constraints enforced in the setter. You can also have calculated or virtual variables by decoupling the instance variable with accessor methods.
Not that I know of. Projects I've worked on have had a family of C macros to stamp out such methods
Yes; I think that's pretty neat. I just worry it's not worth the trouble, it'll just confuse other developers (one more concept they need to fit in their head) and isn't saving much over stamping out such methods manually.
Since Igor Zevaka posted one version of this, I'll post one I wrote a long time ago. This is slightly different -- I observed at the time that most real use of get/set pairs (that actually did anything) was to enforce the value of a variable staying within a pre-determined range. This is a bit more extensive, such as adding I/O operators, where extractor still enforces the defined range. It also has a bit of test/exercise code to show the general idea of what it does and how it does it:
#include <exception>
#include <iostream>
#include <functional>
template <class T, class less=std::less<T> >
class bounded {
const T lower_, upper_;
T val_;
bool check(T const &value) {
return less()(value, lower_) || less()(upper_, value);
}
void assign(T const &value) {
if (check(value))
throw std::domain_error("Out of Range");
val_ = value;
}
public:
bounded(T const &lower, T const &upper)
: lower_(lower), upper_(upper) {}
bounded(bounded const &init)
: lower_(init.lower), upper_(init.upper)
{
assign(init);
}
bounded &operator=(T const &v) { assign(v); return *this; }
operator T() const { return val_; }
friend std::istream &operator>>(std::istream &is, bounded &b) {
T temp;
is >> temp;
if (b.check(temp))
is.setstate(std::ios::failbit);
else
b.val_ = temp;
return is;
}
};
#ifdef TEST
#include <iostream>
#include <sstream>
int main() {
bounded<int> x(0, 512);
try {
x = 21;
std::cout << x << std::endl;
x = 1024;
std::cout << x << std::endl;
}
catch(std::domain_error &e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
std::stringstream input("1 2048");
while (input>>x)
std::cout << x << std::endl;
return 0;
}
#endif
You can also use a getter or setter type method to get or set computable values, much the way properties are used in other languages like C#
I can't think of reasonable way to abstract the getting and setting of an unknown number of values / properties.
I'm not familiar enough with the C++ox standard to comment.
This may be overkill in this case but you should check out the attorney/client idiom for judicious friendship usage. Before finding this idiom, I avoided friendship altogether.
http://www.ddj.com/cpp/184402053/
And now the question, and what if you need a setter as well.
I don't know about you, but I tend to have (roughly) two types of classes:
class for the logic
blobs
The blobs are just loose collections of all the properties of a Business Object. For example a Person will have a surname, firstname, several addresses, several professions... so Person may not have logic.
For the blobs, I tend to use the canonical private attribute + getter + setter, since it abstracts the actual implementation from the client.
However, although your template (and its evolution by Igor Zeveka) are really nice, they do not address the setting problem and they do not address binary compatibility issues.
I guess I would probably resort to macros...
Something like:
// Interface
// Not how DEFINE does not repeat the type ;)
#define DECLARE_VALUE(Object, Type, Name, Seq) **Black Magic Here**
#define DEFINE_VALUE(Object, Name, Seq) ** Black Magic Here**
// Obvious macros
#define DECLARE_VALUER_GETTER(Type, Name, Seq)\
public: boost::call_traits<Type>::const_reference Name() const
#define DEFINE_VALUE_GETTER(Object, Name)\
boost::call_traits<Name##_type>::const_reference Object::Name ()const\
{ return m_##Name; }
#define DECLARE_VALUE_SETTER(Object, Type, Name)\
public: Type& Name();\
public: Object& Name(boost::call_traits<Type>::param_type i);
#define DEFINE_VALUE_SETTER(Object, Name)\
Name##_type& Object::Name() { return m_##Name; }\
Object& Object::Name(boost::call_traits<Name##_type>::param_type i)\
{ m_##Name = i; return *this; }
Which would be used like:
// window.h
DECLARE_VALUE(Window, int, width, (GETTER)(SETTER));
// window.cpp
DEFINE_VALUE(Window, width, (GETTER)); // setter needs a bit of logic
Window& Window::width(int i) // Always seems a waste not to return anything!
{
if (i < 0) throw std::logic_error();
m_width = i;
return *this;
} // Window::width
With a bit of preprocessor magic it would work quite well!
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/tuple/rem.hpp>
#define DECLARE_VALUE_ITER(r, data, elem)\
DECLARE_VALUE_##elem ( BOOST_PP_TUPLE_REM(3)(data) )
#define DEFINE_VALUE_ITER(r, data, elem)\
DEFINE_VALUE_##elem ( BOOST_PP_TUPLE_REM(2)(data) )
#define DECLARE_VALUE(Object, Type, Name, Seq)\
public: typedef Type Name##_type;\
private: Type m_##Name;\
BOOST_PP_SEQ_FOREACH(DECLARE_VALUE_ITER, (Object, Type, Name), Seq)
#define DEFINE_VALUE(Object, Name, Seq)\
BOOST_PP_SEQ_FOREACH(DEFINE_VALUE_ITER, (Object, Name), Seq)
Okay, not type safe, and all, but:
it's a reasonable set of macro I think
it's easy to use, the user only ever have to worry about 2 macros after all, though like templates the errors could get hairy
use of boost.call_traits for efficiency (const& / value choice)
there is more functionality there: getter/setter duo
it is, unfortunately, a set of macros... and will not complain if you ever
it wreaks havoc on the accessors (public, protected, private) so it's best not to intersped it throughout the class
Here is the canonical example then:
class Window
{
// Best get done with it
DECLARE_VALUE(Window, int, width, (GETTER));
DECLARE_VALUE(Window, int, height, (GETTER));
// don't know which is the current access level, so better define it
public:
};
You're solving the wrong problem. In a well-designed application, getters and setters should be rare, not automated. A meaningful class provides some kind of abstraction. It is not simply a collection of members, it models a concept that is more than just the sum of its member variables. And it typically doesn't even make sense to expose individual members.
A class should expose the operations that make sense on the concept that it models. Most member variables are there to maintain this abstraction, to store the state that you need. But it typically shouldn't be accessed directly. That is why it is a private member of the class in the first place.
Rather than finding easier ways to write car.getFrontLeftWheel(), ask yourself why the user of the class would ever need the front left wheel in the first place. Do you usually manipulate that wheel directly when driving? The car is supposed to take care of all the wheel-spinning business for you, isn't it?
This is where I think #defines are still useful.
The template version is complicated and hard to understand - the define version is obvious
#define Getter(t, n)\
t n;\
t get_##n() { return n; }
class Window
{
Getter(int, height);
}
I am sure I have the syntax slightly wrong - but you get the point.
If there was a well known set of templates in, say, boost then I would use them. But I would not write my own.