Say I have the following code:
int ignored = 0;
StreamIgnore si;
si << "This part" << " should be" << ignored << std::endl;
I want that when this code runs si will simply ignore the rest of the stream.
The thing is I want this to be as efficient as possible.
One obvious solution would be to have:
template <typename T>
StreamIgnore& opertaor<<(const T& val) {
//Do nothing
return *this;
}
BUT, if the code was something like:
StreamIgnore si;
si << "Fibonacci(100) = " << fib(100) << std::endl;
Then I'll have to calculate fib(100) before the //Do Nothing part.
So, I want to be able to ignore the rest completely without any unnecessary computations.
To make this request make sense, think that StreamIgnore could be a StreamIgnoreOrNot class, and the c'tor decides whether to ignore the stream or not by either returning *this and use the stream, or a new StreamIgnore() instance and ignoring the rest.
I thought about using Macros some how but could't come up with something that enables me to use this syntax (i.e "si << X << Y...").
I would appreciate it if someone could suggest a way to do that.
Thanks
I 'd obviously use IOstreams with disabling/enabling the output amounting to setting/clearing std::ios_base::failbit. Doing this will readily prevent formatting and writing the data. It won't prevent evaluation of arguments, though. For that purpose I'd use the logical and operator:
si && si << not_evaluated() << when_not_used();
There is no way to do this (without cheating, as you will see below). Your code is only passed the result of fib(100) and as such cannot short-circuit execution here at all.
However, there is a simple hack you can use:
template<typename T> struct is_ignored { static const bool yes = false; };
template<> struct is_ignored<StreamIgnore> { static const bool yes = true; };
#define S(x) if(!is_ignored<remove_reference<decltype(x)>::type>::yes) x
S(x) << "meep\n";
You may have to add some _Pragmas to disable compiler warnings about the fact that this leads to dead code.
Related
I ran into a nasty bug in some of my code. Here's the simplified version:
#include <iostream>
class A
{
public:
std::string s;
void run(const std::string& x)
{
// do some "read-only" stuff with "x"
std::cout << "x = " << x << std::endl;
// Since I passed X as a const referece, I expected string never to change
// but actually, it does get changed by clear() function
clear();
// trying to do something else with "x",
// but now it has a different value although I declared it as
// "const". This killed the code logic.
std::cout << "x = " << x << std::endl;
// is there some way to detect possible change of X here during compile-time?
}
void clear()
{
// in my actual code, this doesn't even happen here, but 3 levels deep on some other code that gets called
s.clear();
}
};
int main()
{
A a;
a.s = "test";
a.run(a.s);
return 0;
}
Basically, the code that calls a.run() use to be used for all kinds of strings in the past and at one point, I needed the exact value that object "a.s" had, so I just put a.s in there and then some time later noticed program behaving weird. I tracked it down to this.
Now, I understand why this is happening, but it looks like one of those really hard to trace and detect bugs. You see the parameter declared as const & and suddenly it's value changes.
Is there some way to detect this during compile-time? I'm using CLang and MSVC.
Thanks.
Is there some way to detect this during compile-time?
I don't think so. There is nothing inherently wrong about modifying a member variable that is referred by a const reference, so there is no reason for the compiler to warn about it. The compiler cannot read your mind to find out what your expectations are.
There are some usages where such wrong assumption could result in definite bugs such as undefined behaviour that could be diagnosed if identified. I suspect that identifying such cases in general would be quite expensive computationally, so I wouldn't rely on it.
Redesigning the interface could make that situation impossible For example following:
struct wrapper {
std::string str;
};
void run(const wrapper& x);
x.str will not alias the member because the member is not inside a wrapper.
I want to present a "pattern of mixin based structure"(is this even a term?) but not quite sure if it would hold up in "some situation".
Basic idea is to generate "type using template class" that multiply inherit mixins. So the type declaration would look like: typedef BaseType<Mixin1, Mixin2, MixinN> Type1;
Some accomplishments by the approach:
Type1's special feature like operator overloads and Constructor overloads are always available.
Explicit type casting overhead is abstracted away by BaseType.
C++ multiple implicit conversion barrier is not a problem.
Usual template mixin approach form here looks like: template<class Base> class Printing : public Base {...}. Main drawback for me with this approach:
It is necessary to explicitly cast Printing to Base to use some of Base's special features, Or have to provide those overloads explicitly (I know it would just be a matter of one line of codes). But in some situation it would be irritating.
That is why I have come up with the idea to generate the base.
Please take a look at the implementation ("some situation"):
#include <iostream>
#include <functional>
#ifdef QT_CORE_LIB
#include <QString>
#endif
template<template<class> class... mixin_t>
class StringType : public mixin_t<StringType<mixin_t...>>...
{
std::string _value;
public:
StringType() : _value("") {}
StringType(const StringType &other) = default; // Copy
StringType(StringType &&other) = default; // Move
#ifdef QT_CORE_LIB
StringType(const QString &value) { this->_value = value.toStdString(); }
#endif
StringType(const std::string &value) { _value = value; }
StringType(const char *value) { _value = value; }
template<template<class> class T>
StringType(const StringType<T> &value)
{
_value = static_cast<const std::string &>(value);
}
StringType &operator=(const StringType &rhs) = default; // copy assign
StringType &operator=(StringType &&rhs) = default; // Move assign
#ifdef QT_CORE_LIB
operator QString() const { return QString::fromStdString(_value);}
#endif
operator std::string() const { return _value; }
operator const char *() const{ return _value.c_str(); }
};
template<class this_t> struct _empty_mixn {};
template<class this_t> struct ToStringMixin
{
this_t toString() const { return *static_cast<const this_t *>(this); }
};
template<class this_t> struct StringPrinterMixin
{
void print() const
{
std::cout << "From the printer: " << *static_cast<const this_t *>(this);
}
};
typedef StringType<_empty_mixn> String;
typedef StringType<ToStringMixin> Message;
typedef StringType<ToStringMixin, StringPrinterMixin> PrinterAttachedString;
int main()
{
Message msg1(String("msg1\n"));
std::cout << msg1;
std::cout << "toString() : " << msg1.toString();
Message msg2 = String("msg2\n");
std::cout << msg2;
std::cout << "toString() : " << msg2.toString();
Message msg3(std::string("msg3\n"));
std::cout << msg3;
std::cout << "toString() : " << msg3.toString();
Message msg4 = std::string("msg4\n");
std::cout << msg4;
std::cout << "toString() : " << msg4.toString();
Message msg5("msg5\n");
std::cout << msg5;
std::cout << "toString() : " << msg5.toString();
Message msg6 = "msg6\n";
std::cout << msg6;
std::cout << "toString() : " << msg6.toString();
std::cout << "\n---------------------\n\n";
PrinterAttachedString str1(String("str1\n"));
std::cout << str1;
std::cout << "toString() : " << str1.toString();
str1.print();
PrinterAttachedString str2 = String("str2\n");
std::cout << str2;
std::cout << "toString() : " << str2.toString();
str2.print();
PrinterAttachedString str3(std::string("str3\n"));
std::cout << str3;
std::cout << "toString() : " << str3.toString();
str3.print();
PrinterAttachedString str4 = std::string("str4\n");
std::cout << str4;
std::cout << "toString() : " << str4.toString();
str4.print();
PrinterAttachedString str5("str5\n");
std::cout << str5;
std::cout << "toString() : " << str5.toString();
str5.print();
PrinterAttachedString str6 = "str6\n";
std::cout << str6;
std::cout << "toString() : " << str6.toString();
str6.print();
return 0;
}
So, my questions:
Would it be practical use this in a situation where operator overloading/implicit casting feature necessary?
Does it seem, there would be a necessity of virtual inheritance?
Are there any other implementation like this (My search was a failure)?
Finally, is there a thing called "meta mixin" that would provide a type's special features?
Edit: In response to Phil1970's answer:
I am going to start with the answer to the question 3.
This approach leads to class proliferation: I totally agree. One big drawback I have to admit.
Increases coupling. Not sure how it increases coupling. *1
The rests marked there, I believe is not applicable due to the fact that StringType is quite final. And StringType does not know or about mixed class for real. *1
Now for the answer to the question no 1.
It is usually best to avoid implicit conversion.
The rests to me is ok as long as it is final. *2
With previous question gone (huge thanks to Phil) arose new questions.
*1: It is just one header-only, StringStyle does not depend on mixins and I see no reason to be so. And certainly this it can use private header if somehow becomes necessary. Then how it enforcing coupling?
*2: Just looking for opinions or to get me corrected.
Thanks a lot.
For your question:
It is usually best to avoid implicit conversion. Also you won't be able to reuse std::string operators like +, += with that kind of approach without adding a lot one line function. The wrapper class bring you nothing except adding more conversions as you would then use you new string type and with the mixin approach, this is even worst as you need to also convert between your own types.
Why would you use virtual inheritance? Do you really want to derive from multiple classes that have a common base and that have their own data.
As this is a bad design, you probably won't find many people doing it. Your design increase coupling, lead to class proliferation, increase type conversions and make maintenance harder among other things.
I believe, there is no such thing.
For simple functions like those above, the preferred approach would be to define a namespace (or many if you have a lot of functions that could somehow be categorized like maybe file name manipulation) and then have free functions inside it.
By using a namespace, you have a few advantages:
If you call a lot of functions, you can always add an using statement inside your function or source file (never in a header file).
Auto suggestion will work well to find those function.
If some of the original mixin maintain state, then you should do an helper class. This could be the case for a class like an HTML builder that might have functions like AddTag, Add Attribute, AddEncodedUrl etc that could be used to create an HTML document.
One big advantage of this approach is that coupling is much looser than in your design. For example, a file pair (header and source) would contains all functions used for the Printer. If you need that, you don't have to create a new class that use some combination of mixin.
One big problem with your approach, is that with time you will have a lot of different StringType<…> If you have 5 mixins that could be used, you have 2^5 = 32 classes. At that point, it is almost sure that you will often need the mixin you didn't include and then you have cascading change if the call it deep. And if you use template everywhere then you will have compilation slowdown and probably some code bloat.
Implicit conversion is also considered to be best avoid in most cases by most experts. If you have multiple conversion from and to many classes, at some point you will have unexpected conversion or ambiguities. Making some conversion explicit can limit the problem. Usually is it best to use explicite conversion as it was done by experts in std::string. You have to call member function c_str() if you want a C style string.
For example, since your StringType class define conversion to both const char * and QString, then if you have a method that accept both (maybe an Append function), then you have a conflict.
If you really want conversion, then use named method instead (for ex. AsQString(), c_str(), tostdstring()...). It help ensure that all conversion are intended. It make it easier to find them and it is certainly better that explicit cast like you have done in a few place in your code. While static_cast and other casts are sometime useful, then can also hide some problem when code is refactored as in some case, the cast might compile while not being correct. This would be the case if you cast to a derived class and at some point decide to change the derived class for something else and forget to update some casts.
You should select the most appropriate string for your application and do conversion when required. In a large application, you might use one type for the UI (ex. CString or QString) while using standard string in librairies that are shared across platforms or with third party library. Some time those libraries have their own string class too. Your selection should try minimize useless conversions.
I have this sample block of code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
string blank = " ";
cout << "Hello" << blank << "47";
}
I have a lot of cout's of this type in my original code.
I want to be able to change the blank string to setw(2) function without having to replace blank with setw(2) on each and every cout I have in my code.
So is there a way to set a cpp function to a variable?
So I can call the function by typing the name?
for example:
func blank = setw(2);
cout<< "Hello" << blank << "47";
The type of std::setw(x) is unspecified, but you don't need to know it.
You can just use auto:
auto blank = std::setw(2);
As #StoryTeller noted, while this should work on sane implementations, it's not guaranteed to.
A safer option would be to make a class with overloaded <<:
struct blank_t {} blank;
std::ostream &operator<<(std::ostream &s, blank_t)
{
return s << std::setw(2);
}
std::setw is a manipulator. Its type is unspecified and implementation specific.
So is there a way to set a cpp function to a variable?
With C++11 you can use function objects, notably std::function. And you also have lambda expressions.
I am not sure you want to use it in your case.
So learn to use your source code editor. Replace every occurrence of blank with the appropriate stuff, that is std::setw(2) .... That makes your code more readable. Good editors are able to do that easily.
You could abuse the preprocessor, and have
#define blank setw(2)
but in your case that is a bad idea (because the code remains unreadable). Even using auto as answered by HolyBlackCat keeps your code unreadable and confusing.
Code is much more often read than written. Keep it readable (even by yourself, in a few weeks).
If you have a huge (million-line) project, spend perhaps a few minutes to write some script to change your source code in such case. BTW, with GNU emacs it is easy (since emacs is a scriptable editor).
An alternative solution is to write a small wrapper class whose only purpose is to provide an overloaded operator<< for an encapsulated referenced object. You can templatise that class so it works with everything that you could feed to an std::ostream in the first place.
Here is an example:
#include <iostream>
#include <iomanip>
#include <string>
template <class T>
struct Blank {
Blank(T const& t) : t(t) {}
T const& t;
};
// utility function so that you can use type deduction at the call site:
template <class T>
Blank<T> blank(T const& t) {
return Blank<T>(t);
}
template <class T>
std::ostream& operator<<(std::ostream& os, Blank<T> const& blank) {
os << std::setw(2) << blank.t;
return os;
}
int main() {
std::cout << "Hello" << blank("4") << blank(7) << blank(std::string("8")) << '\n';
}
It's not exactly the syntax you've asked for, but it comes pretty close.
You also have to make sure that no encapsulated object is destroyed before it's used in operator<< (because then you'd have undefined behaviour due to a dangling reference), but that's easy to accomplish if never create named Blank objects.
i'm trying to build a general purpose template function which should function with 2 different type of structure i'll write an example
struct sa {
int a;
int b;
char d;
}
struct sb {
int a;
int b;
int c;
}
template < class T>
void f_print(T & s_passed, bool s_typeB){
std::cout << s_passed.a << endl ;
std::cout << s_passed.b << endl ;
if(s_typeB == false){
std::cout << s_passed.d << endl ;
}else{
std::cout << s_passed.c << endl ;
}
}
then in main:
{
struct sa str_TEST_A ;
struct sb str_TEST_B ;
f_print(str_TEST_A,false);
f_print(str_TEST_B,true);
}
now , this is a short example of my issue where i'm handling much more complicated structures, anyway what i get is
error: 'struct sa' has no member named 'd'
the problem is that the gnu c++ compiler didn't recognize that not all operations in the function are execute when struct sa is passed, and d is printed only when sb is passed,
how i can fix this without creating a duplicated function 1 for each structure type?
thank you :)
Francesco
You could move the specialized parts in separate functions and call these from your generic template:
void f_print_special(sa & s_passed) {
std::cout << s_passed.d << endl ;
}
void f_print_special(sb & s_passed) {
std::cout << s_passed.c << endl ;
}
template <class T>
void f_print(T & s_passed) {
std::cout << s_passed.a << endl ;
std::cout << s_passed.b << endl ;
f_print_special(s_passed);
}
sth has the correct answer. However, if you need a more generic solution, in that say the function that accepts sb type could accept any type that implements the concept "has C" (or whatever) then you need to use tag based dispatch. I'd suggest looking it up because though I might be able to describe one hypothetical situation that may or may not resemble your real problem, I couldn't get them all.
It's not just g++. That's invalid C++. Every statement in a function (template or not) must be valid, even if you can "prove" it's not executed.
What's so bad about giving them separate functions? Of course, you can deal with some common subparts by calling another subfunction.
If you want the functions to have the same name, go ahead and do that. Function overloading will handle it.
Perhaps this is just a test case for you in writing templates but a more natural implementation would be to have sa and sb inherit from a common base struct sbase say, with members a and b only, and then have sa and sb implement their own operator<<, delegating to the base operator<< for the common parts.
i have a complex program with weird bug that some int value is down to zero unexpectedly.
so i want tracking this built-in type value, then i could debug easily.
to do that, i made following ValueWatcher template class so i could track almost changes of value except when ValueWatcher is dereferencing. (i made these dereferencing operators because the program needs int *, &)
template <typename T>
class ValueWatcher
{
public:
ValueWatcher(const T &val)
{
cout << "constructor with raw value " << val << endl;
_cur = _old = val;
}
ValueWatcher(const ValueWatcher& vw)
{
cout << "constructor with ValueWatcher " << vw._cur << endl;
_cur = vw._cur;
}
ValueWatcher& operator=(const ValueWatcher &rhs)
{
cout << "operator= with ValueWatcher " << rhs._cur << endl;
_cur = rhs._cur;
onChanged();
return *this;
}
ValueWatcher& operator=(const T &val)
{
cout << "operator= with " << val << endl;
_cur = val;
onChanged();
return *this;
}
int *operator&()
{
cout << "addressing operator" << endl;
// can't track anymore!!!!!!!!!!!!!!!!!!!!!!!!!
return &_cur;
}
operator int&()
{
cout << "operator int&" << endl;
// can't track anymore!!!!!!!!!!!!!!!!!!!!!!!!!
return _cur;
}
operator int&() const
{
cout << "const operator int&" << endl;
return _cur;
}
operator int() const
{
cout << "operator int" << endl;
return _cur;
}
private:
void onChanged()
{
// update old and do proper action
}
T _cur;
T _old;
};
the problem is, when client code wants int & or int * of ValueWatcher, - it can gives int & or int * anyway but - int * or & cannot hold ValueWatcher instance, so can't tracking anymore.
is there anyway to solve this? i think it can be solved by returning reference or pointer class instance instead of just returning & or * of built-int type. but i don't know how to do that.
in addition-
i can't run this program with debugger. the problem occurs only in REAL environment and very hard to reproduce.
If you can reproduce the behavior when running in a debugger, you should be able to set a value change or memory change breakpoint. This is probably easier than introducing a proxy implementation.
Its probably not the best solution, but what if your * or & return a pointer/reference to your value watcher? Otherwise I would forbid the use of * or &. (By not implementing it or making it private).
I don't think this is possible. Once you return an int* or int&, you've lost the ability to track anything. The only way (and the correct way, IMO) to do it that I can think of is to use a debugger and set a watch point with an appropriate condition. When the condition is met the debugger will interrupt and halt the program so you can inspect the memory, call stack, etc.
If you can spare a PAGE_SIZE bytes for your variable, then you can lock this part of memory using VirtualProtect (if you're on windows) - you can set read only access, for example. After that, anything that tries to access that variable will crash the program (so you'll be able to write memory dump and pinpoint routine that changes variable). I used this technique to pinpoint similar problem (multithreaded app, something was randomly overwriting memory blocks). If you can't debug machine immediately, try writing dumps using MiniDumpWriteDump . You will be able to debug memory dumps using WinDBG or Visual Studio.
If you're seriously desperate:
#define int ValueWatcher<int>
In a better scenario, you'd use
//typedef int intt;
typedef ValueWatcher<int> intt;
Then re-write all your code that wants an int and replace it. Replace int* with intt*. Replace int& with intt&.
You say you only see this problem when not debugging, so I'm guessing you have a bug which is obscure and can only be seen when building with optimizations. There are a couple possible explanations for this behavior:
You have a race condition somewhere
You didn't initialize a variable properly... so when building with optimizations you're values are initialized differently than when debugging.
You have a buffer overrun somewhere which is writing over one of your variables. Again, this could be something you only see when built with optimizations... When you build for debugging the compiler is going to leave extra space around variables on the stack... which acts as a cushion and can keep some bugs from revealing themselves.
Here is a relevant SO post which explains these issues in more detail:
Program only crashes as release build -- how to debug?