How to tell what template C++ generated - c++

I have a C++ template function that looks like
template <class T>
void Item::SetValue(T value){
std::ostringstream oss;
oss << value;
this->value = oss.str();
}
It's been working fine for years until today when my OS (vxworks) threw an SPE exception at me. This basically means I was trying to do floating point arithmetic in a task context that doesn't allow it. This would be fine if I was indeed doing any floating point stuff, but I in fact am just passing a uint32_t to this function. However there are 100s of calls to this function elsewhere from other modules, so who knows what C++ has generated.
I need to know for sure this is the problem (I'm 99% sure) so I want to know if there's any way for me to figure out what function C++ compiler generated for that call. Is there any way?
I may have to ask a new question. I found in the debugger that it is using Item::SetValue<unsigned int> and that it is actually throwing the exception in std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char>>>::do_put (at least, i think). This is the instruction output, and it is failing in evstdd which is definitely in the SPE set. Still don't know why it wants to do any floating point stuff.
Is it possible that
oss << value
Will always treat value as a float, just in case? IE in std::num_put? I don't know how I'll get around this.
Instruction set

Yes, you can use type_traits
if(std::is_same_v(T, uint32_t)) { /*debug info*/ }

The classical solution is to add to the body of the function:
static_assert(!std::is_floating_point_v<T>);

Related

Output long double to console

I tried to output a long double to the console directly using qDebug() and indirectly via QString::number() but both do not accept long double.
Is it true that there is no easy way of printing a long double floating point number to the console using Qt? Why?!
You can provide your own overload of operator<<():
QDebug& operator<<(QDebug& d, long double f)
{
return d << static_cast<double>(f);
}
This won't show you any extra precision, of course, but may be what you need.
Be aware, however, that a future version of Qt might implement such a function, putting you in violation of the One-Definition Rule. To avoid this, you should guard it with an appropriate #if test for the exact Qt version (or range of versions) that you have verified do not provide a conflicting definition. Also, please consider contributing your implementation to Qt.
There's no overarching reason. At least as of Qt 5.6, nobody bothered to implement it. That's all.

C++ Calling different functions by string name

I am relatively new to C++ - I leanerd it some 6+ years ago, but have never really used it until some months ago.
What is the scenario:
Considerably large system with a lot of modules.
Desired Output:
Modules (namely X) "expose" certain functions to be called over network and have the result sent back to the caller (namely Y)
The caller Y doesn´t know any info about X, despite what was exposed by the library (function name and parameters).
The calling of function in X from the library will have to happen through a string received from Y - or a set of strings, as there will be parameters as well.
Ideally what I want to have is something as generic as possible with variable return/paramaters types, or some kind of type-erasure - owing to the fact that I don´t know which functions each module will want to expose. I reckon its quite utopic to get something like that running in C++. But hopefully with pre-determined possible return/parameter types, it is feasible. The communication is not a problem for now, what matters is what should be done in the module side.
Question:
Would it be possible to accomplish such thing using C++ and Boost ? I would be really greateful if someone could give me some guidelines - literature/tutorials/(pseudo)code examples and so on and so forth. I am ofc not expecting a full solution here.
Possible solution:
I am a little bit lost as to which "functionalities" of the languages I can/should use - mainly due to my restrictions in the project.
I thought about using Variadic Templates and found the question below, which really helps, the only problem is that Variadic Templates are not supported in VS2010.
Generic functor for functions with any argument list
After some extensive research in the Web, the closest answer I got was this:
map of pointers to functions of different return types and signatures
The scenario is pretty much the same. The difference, however, seems to me that the OP already knows beforehand the return/parameters the functions he will be using. Due to my low reputation (I just joined) I unfortunately cannot ask/comment anything there.
TBH I didn´t get that well how to accomplish what the selected answer explains.
Using maps is a way, but I would have to store objects which contains function pointers (as also answered in the question), but as it is possible to see in the provided code by the user, it does have some hard-coded stuff which I wasn´t desiring to have.
Further clarifications:
Yes, I am restricted to use C++ AND VS2010 SP1.
No, despite Boost, I cannot use any other 3rd library - it would be great to be able to use some Reflection libraries such as CPGF http://www.cpgf.org/ (even though I am not 100% sure if thats what I really need)
Minor Edit:
- Scripting language bindings (such as LUA) are indeed a way to go, yet I didn´t want to include it in the project.
I hope someone can shed light on this problem!
Thanking in advance for any input!
Looks like you're needed a little reflection module. For example we have a struct of method info such as:
struct argument_info {
std::string name;
std::string type;
std::string value;
}
struct method_info {
std::string method_name;
std::string return_type;
std::list<argument_info> arguments;
}
then compile a dll with all exported functions
extern"C" __declspec(dllexport) void f1(int a, int b){/*...*/}
extern"C" __declspec(dllexport) int f1(std::string a, int b, char* c){ return x; }
in the interpreter's code:
void call_function(method_info mi, argument_info& t_return)
{
/* let g_mi be a map, where key is a std::string name of the method and the
value is method_info struct */
if(!g_mi->find(mi.method_name))
throw MethodNotFindException
if(g_mi[mi.method_name].arguments.size() != mi.arguments.size())
throw InvalidArgumentsCountException;
for(int i = 0; i < g_mi[mi.method_name].arguments.size(); i++)
{
if(g_mi[mi.method_name].arguments[i].type != mi.arguments[i].type)
throw InvalidArgumentException;
}
t_return = module->call(mi.arguments);
}
I hope it may help you.

Compile time RAII type of behavior using C++

I know it sounds a bit wierd but this is what I want to do: Lets say I have a function void f() and I want to add tracing for this method. I want to trace the enrty of this function and the exit of the function by having trace messages such as "Entered function f" and "Exited function f". I don't want to add manual trace entries for the entry and exit as I might missout on some of return paths. So is possible to use the template magic at compile time and have these strings automatically generated. i.e. what I want to achieve is
void f()
{
some_template<magic>("f");
}
This should add a trace message "Entered function f" in constructor and "Exited function f" in destructor. I want it compile time and don't want to create any runtime objects. Is it possible in C++? any pointers where I can find more info if this can be achieved?
The point at which the method is left is only known at runtime, since any kind of exception can happen at any point in your code (generally speaking). Hence, no compile-time solution is possible here.
You really need to ask your debugger or compiler to perform this job. There's no way that you can use RAII without creating an object, and in addition, no template can have access to the name of your function.
However, if you can accept an object, then it's no big deal.
class tracer {
std::string exit;
public:
tracer(std::string entry, std::string exit_)
: exit(exit_) {
std::cout << entry;
}
~tracer() { std::cout << exit; }
};
void f() {
tracer scope("Oh hai, I is entering f()", "Oh bai, I is leaving f()");
}
All code is created at compile time anyway, so what's the problem with a class? The compiler will stick the constructor and destructor calls where they belong, and that's precisely what you want. The runtime cost is calling those functions, which is entirely unavoidable since it's your goal.
It may appear that saving "f" would cost you a char const*, but any decent optimizer will note that the string literal is a constant that doesn't change throughout the function, so it doesn't need to be stored but can be reloaded. Let the optimizer decide whether it's efficient to cache the pointer; I can't predict it.
If you are really serious about this, using AspectC++ is one option. However, the threshold for doing so is quite high and I think you'll find yourself flooded with output if you do anything like this. A better option would be to use the debugger (setting breakpoints that print some output) or good ol' printf/cout wrapped in a class like DeadMG suggests. The ___FILE___ and ___LINE___ could be useful input to such a class.

How do I prevent/suppress SIGFPE in C++?

I'm trying to convert a double to float as well as various integer types inside a dll, which is used as a Game Maker extension. I don't need a sensible result if the double doesn't fit the range of the target types, so I simply used a static_cast.
Everything works as intended when I call this code from my own test C++ application, but when it's called from Game Maker, range errors raise SIGFPE for some reason, which leads Game Maker to terminate my program with an error message.
I don't need sensible results for out-of-range conversions, but crashing is a no-no. I tried using llround instead of a cast, but it also raises the signal.
I also tried catching the signal myself by using signal(SIGFPE, SIG_IGN); right before the conversion, but it didn't change the behaviour at all. Maybe the ominous comment in the mingw signal.h has something to do with that: "SIGFPE doesn't seem to work?"
I checked the source code of a different dll used in a Game Maker extension, and the binary provided by the author performs simple cast conversions without a problem. When I compile the source myself however, the SIGFPE problem is present again. I am guessing that the author used a different compiler, but I'd prefer to stay with mingw if possible.
So, how do I either perform these conversions safely, or prevent the signal from being generated when I perform them with a simple cast? I'm using mingw-g++ 4.5.0 to compile at the moment.
Here's the function where the problem happens:
template<typename ValueType>
static double writeIntValue(double handle, double value) {
boost::shared_ptr<Writable> writable = handles.find<Writable>(handle);
if(writable) {
// Execution reaches this point
ValueType converted = static_cast<ValueType>(value);
// Execution doesn't reach this point if e.g. ValueType
// is short and value is 40000
writable->write(reinterpret_cast<uint8_t *>(&converted), sizeof(converted));
}
return 0;
}
The good solution is to perform the conversion correctly by ensuring that the source value is within the range of the target type before casting. So my code from the question could be corrected like this:
ValueType converted;
if(value >= std::numeric_limits<ValueType>::max()) {
converted = std::numeric_limits<ValueType>::max();
} else if(value <= std::numeric_limits<ValueType>::min()) {
converted = std::numeric_limits<ValueType>::min();
} else {
converted = static_cast<ValueType>(value);
}
Another option is to use numeric_cast from the Boost libraries, which throws an exception if the source value is out of range, so it has defined behaviour for all conversions.
The documentation of the Boost Numeric Conversion library contains some helpful information about how the standard defined certain conversions.
Thanks to rve for providing the correct suggestion in his answer, but unfortunately his example code is flawed, and I wanted to add some additional pointers that helped me.
Since you are using a DLL, are you sure the DLL is compiled in the same way as the program expects it? Maybe some 32/64 bit mismatch?
Also, SIGFPE can also be raised when there is an under/overflow when converting.
You can enable/disable the signal raised by this overflow by setting the mask using _FPU_SETCW (it's in fpu_control.h) My guess is that Game Maker enables this and your test program not.
I never tried this and I'm not sure mingw also has this but I hope this helps a little.
edit:
Why not making sure an overflow does not happen?
Something like:
if (value > std::numeric_limits<ValueType>::max())
{
value = std::numeric_limits<ValueType>::max();
}
else if (value < std::numeric_limits<ValueType>::min())
{
value = std::numeric_limits<ValueType>::min();
}
ValueType converted = value;
probably it's not related with conversion itself but with trying to access invalid memory (maybe stack corruptions or something like that). can you provide some code snippet?

accessing element of boost sparse_matrix seems to stall program

I've got a strange bug that I'm hoping a more experience programmer might have some insight into. I'm using the boost ublas sparse matrices, specifically mapped_matrix, and there is an intermittent bug that occurs eventually, but not in the initial phases of the program. This is a large program, so I cannot post all the code but the core idea is that I call a function which belongs to a particular class:
bool MyClass::get_cell(unsigned int i, unsigned int j) const
{
return c(i,j);
}
The variable c is defined as a member of the class
boost::numeric::ublas::mapped_matrix<bool> c;
When the bug occurs, the program seems to stop (but does not crash). Debugging with Eclipse, I can see that the program enters the boost mapped_matrix code and continues several levels down into std::map, std::_Rb_tree, and std::less. Also, the program occasionally traces down to std::map, std::_Rb_tree, and std::_Select1st. While code is executing and the active line what's in memory changes in _Rb_tree, execution never seems to return in the level of std::map. The line in std::map the program is stuck on is the return of the following function.
const_iterator
find(const key_type& __x) const
{ return _M_t.find(__x); }
It seems to me that there is some element in the c matrix that the program is looking for but somehow the underlying storage mechanism has "misplaced it". However, I'm not sure why or how to fix it. That could also be completely off base.
Any help you can provide would be greatly appreciated. If I have not included the right information in this question, please let me know what I'm missing. Thank you.
Some things to try to debug the code (not necessarily permanent changes):
Change the bool to an int in the matrix type for c, to see if the matrix expects numeric types.
Change the matrix type to another with a similar interface, possibly plain old matrix.
Valgrind the app (if you're on linux) to check you're not corrupting memory.
If that fails, you could try calling get_cell every time you modify the matrix to see what might be causing the problem.
Failing that, you may have to try reduce the problem to a much smaller subset of code which you can post here.
It might help if you tell us what compiler and OS you're using.
Is this part of a multithreaded program?
I ask, because usually when I see problems in STL, it ends up being a problem with unsynchronized access.