Operating on a string before runtime - c++

I have a string:
B<T>::B() [with T = int]
Is there any way I can get
B<T> [with T = int] from this before run time somehow? :)
Simplifying: Is there any way to get X & Y separately from a static string XY defined as a preprocessor macro in any form before runtime?

In current C++ I cannot think on a way to split the string at compile time. Most of the template tricks will not work on string literals. Now, I imagine that you want this to use in some sort of logging mechanism and you want to avoid the impact of performing the split at runtime in each method invocation. If that is the case, consider adding a function that will perform the operation and then in each function a static const std::string to hold the value. That string will be initialized only once in the first call to the function:
#define DEFINE_LOG_NAME static const std::string _function_name( parse( __PRETTY_FUNCTION__ ) )
#define LOG_NAME( level ) do { DEFINE_LOG_NAME; log( level, _function_name ); } while (0)
std::string parse( std::string const & pretty ) {
// split here, return value
}
template <typename T>
struct B {
B() {
LOG_NAME( DEBUG );
}
};
(I have not tested this, so you might need to fiddle with it)
This will have some runtime impact, but only once for each function. Also note that this approach is not thread safe: if two threads simultaneously call a method that has not been called before there will be a race condition.

is this what you wanted ?
#define X "X"
#define Y "Y"
#define XY string(X) + Y
static string s = XY;

Related

Alternatives to stringifying the variable name in C++11

In my code, I have repeatedly this expression:
T foo;
do_sth(foo, "foo");
I am considering stringifying the variable name, like this:
#define VARNAME(Var) (#Var)
void do_sth_new(T foo) { do_sth(foo, VARNAME(foo)); };
T foo;
do_sth_new(foo);
Is it good practice? Is there any better alternative in C++11?
As you show it, it doesn't work since VARNAME(foo) will always be "foo" (as this is the parameter's name). You have to write do_sth_new itself as macro:
#define do_sth_new(_foo) \
do { do_sth(_foo, #_foo); } while (false)
Only then will this:
T bar;
do_sth_new(bar);
generate "bar".
And no, there is no alternative to using the preprocessor since this is an operation on the lexical level. You'd need LISP-level modification of the AST in the language to have a better solution, which is unlikely to ever happen.
Sadly, no. There is still no solution (not even in C++17) to this problem. There might be something once static reflection will be added to C++. But for the time being you're stuck with the macro.
There is no real way to avoid the macro to do the stringify.
What you can do is dress it in a more c++ object-oriented way, especially if you want to do multiple different methods that take an object and its var name, and if this is a debug feature you might want to disable in production.
So I'm proposing you declare a template class DebugContextWrap, and objects of this type (or const ref) can be passed into the function as a single parameter, instead of having 2 parameters.
The one downside is that where your function code actually wants to access the actual value then you would have to perform an indirection through operator -> or data() as you do for iterators.
You could then write a macro that generates instances of DebugContextWrap - something like:
template class FooType
class DebugContextWrap
{
FooType& fooVal;
const char* debugName;
const char* debug__FILE__val;
const int debug__LINE__val;
public:
DebugContextWrap(FooType& fooVal,
const char* debugName, const char* debug__FILE__val, const int debug__LINE__val)
{ ... }
DebugContextWrap(FooType& fooVal) // implicit when caller doesn't use DEBUG_WRAP
{ ... }
FooType* operator ->()const
{ return &foo; }
FooType& operator *()const
{ return foo; }
FooType& Data()const
{ return foo; }
const char* DebugName()const
{ return debugName; }
};
#define DEBUG_WRAP(foo) \
DebugContextWrap<decltype foo>(foo, #foo, __FILE__, __LINE__)
void do_sth(const DebugContextWrap<FooType>& foo);
do_sth(DEBUG_WRAP(foovar));

Inject additional data in a method

I am adding the new module in some large library. All methods here are implemented as static. Let me briefly describe the simplified model:
typedef std::vector<double> TData;
double test ( const TData &arg ) { return arg ( 0 ) * sin ( arg ( 1 ) + ...;}
double ( * p_test ) ( const TData> &arg) = &test;
class A
{
public:
static T f1 (TData &input) {
.... //some computations
B::f2 (p_test);
}
};
Inside f1() some computations are performed and a static method B::f2 is called. The f2 method is implemented by another author and represents some simulation algorithm (example here is simplified).
class B
{
public:
static double f2 (double ( * p_test ) ( const TData &arg ) )
{
//difficult algorithm working p_test many times
double res = p_test(arg);
}
};
The f2 method has a pointer to some weight function (here p_test). But in my case some additional parameters computed in f1 for test() methods are required
double test ( const TData &arg, const TData &arg2, char *arg3.... ) { }
How to inject these parameters into test() (and so to f2) to avoid changing the source code of the f2 methods (that is not trivial), redesign of the library and without dirty hacks :-) ?
The most simple step is to override f2
static double f2 (double ( * p_test ) ( const TData &arg ), const TData &arg2, char *arg3.... )
But what to do later? Consider, that methods are static, so there will be problems with objects.
Updated question
Is it possible to make a pointer to a function dependent on some template parameter or do something like that
if (condition) res = p_test(arg);
else res = p_test2(arg, arg2, arg3);
without dirty hacks
Not gonna happen. If you can't modify the source of a function taking a function pointer, you'll have to use an exception vomit to gain the extra arguments. If you had a C++11 compiler (that does not exist yet) which supports thread_local, it's theoretically possible to do something better, or you could use OS-specific TLS. But as of right now, the only portable solution is an exception vomit.
void f(void(*fp)()) { fp(); }
void mah_func() {
try {
throw;
} catch(my_class* m) {
m->func();
}
}
int main() {
my_class m;
try {
throw &m;
} catch(my_class* p) {
f(mah_func);
}
}
Alternatively, in your scenario, modifying f2 doesn't seem to be impossible, only difficult. However, the difficulty of altering it to take a std::function<double(const TData&)> would be very low- all you'd have to do is change the argument type, thanks to operator overloading. It should be a very simple change for even a complex function, as you're only changing the type of the function parameter, all the call sites will still work, etc. Then you can pass a proper function object made through bind or a lambda or somesuch.
"avoid changing", well that's a bit difficult.
however, you can use a static variable to pass arguments across calls of functions that don't pass the arguments.
remember that if there is more than one thread using those function, you need to either use thread local storage (which is what i recommend for that) or else ensure proper mutual exclusion for use of those variables, where in the case of a single variable shared between all the threads means exclusion all the way down the call chain. but do use thread local storage if threading is a problem. and if no threading problem, well, no problem! :-)

What are good cases for using __if_exists?

When do I use __if_exists without writing tons of crappy code?
Looks like this keyword is like C preprocessor directive, but is processed after preprocessor. And IntelliSense doesn't parse it and highlight code as dead or alive. These together make analysis of code written with __if_exists really non-trivial.
So far I found only one relatively safe case. We have a container class that takes an address of stored object. When a class stored has an overloaded operator& that overloaded operator is called and this causes problems.
So I added the following check:
__if_exists( T::operator& ) {
static_assert( false );
}
and now the code at least won't compile if there's an operator& member function is the type stored.
IMO this use case is quite clear and easy to read.
What other cases are there of using __if_exists without getting tons of unreadable code?
Though I'm not sure this is always possible or useful, __if_exists can be
used as static if in D language in a sense.
For example, the following code prints b.
template< bool > struct static_if_t;
template<> struct static_if_t< true > {};
#define STATIC_IF( c ) __if_exists ( static_if_t< (c) > )
#define STATIC_UNLESS( c ) __if_not_exists( static_if_t< (c) > )
struct X {
static bool const v = false;
};
STATIC_IF( X::v ) {
void f() { puts("a"); }
}
STATIC_UNLESS( X::v ) {
void f() { puts("b"); }
}
int main() {
f(); // prints "b"
}
I think you can use it to distinguish unions and classes, since classes do have constructors and unions don't.
You'd want this in e.g. boost::type_traits::is_class<T> and boost::type_traits::is_union<T>

How can one make a 'passthru' function in C++ using macros or metaprogramming?

So I have a series of global functions, say:
foo_f1(int a, int b, char *c);
foo_f2(int a);
foo_f3(char *a);
I want to make a C++ wrapper around these, something like:
MyFoo::f1(int a, int b, char* c);
MyFoo::f2(int a);
MyFoo::f3(char* a);
There's about 40 functions like this, 35 of them I just want to pass through to the global function, the other 5 I want to do something different with.
Ideally the implementation of MyFoo.cpp would be something like:
PASSTHRU( f1, (int a, int b, char *c) );
PASSTHRU( f2, (int a) );
MyFoo::f3(char *a)
{
//do my own thing here
}
But I'm having trouble figuring out an elegant way to make the above PASSTHRU macro.
What I really need is something like the mythical X getArgs() below:
MyFoo::f1(int a, int b, char *c)
{
X args = getArgs();
args++; //skip past implicit this..
::f1(args); //pass args to global function
}
But short of dropping into assembly I can't find a good implementation of getArgs().
You could use Boost.Preprocessor to let the following:
struct X {
PASSTHRU(foo, void, (int)(char))
};
... expand to:
struct X {
void foo ( int arg0 , char arg1 ) { return ::foo ( arg0 , arg1 ); }
};
... using these macros:
#define DO_MAKE_ARGS(r, data, i, type) \
BOOST_PP_COMMA_IF(i) type arg##i
#define PASSTHRU(name, ret, args) \
ret name ( \
BOOST_PP_SEQ_FOR_EACH_I(DO_MAKE_ARGS, _, args) \
) { \
return ::name ( \
BOOST_PP_ENUM_PARAMS(BOOST_PP_SEQ_SIZE(args), arg) \
); \
}
At 40-odd functions, you could type the wrappers out by hand in an hour. The compiler will check the correctness of the result. Assume an extra 2 minutes for each new function that needs wrapping, and an extra 1 minute for a change in signature.
As specified, and with no mention of frequent updates or changes, it doesn't sound like this problem requires a cunning solution.
So, my recommendation is to keep it simple: do it by hand. Copy prototypes into source file, then use keyboard macros (emacs/Visual Studio/vim) to fix things up, and/or multiple passes of search and replace, generating one set of definitions and one set of declarations. Cut declarations, paste into header. Fill in definitions for the non-passing-through functions. This won't win you any awards, but it'll be over soon enough.
No extra dependencies, no new build tools, works well with code browsing/tags/intellisense/etc., works well with any debugger, and no specialized syntax/modern features/templates/etc., so anybody can understand the result. (It's true that nobody will be impressed -- but it will be the good kind of unimpressed.)
Slightly different syntax but...
#include <boost/preprocessor.hpp>
#include <iostream>
void f1(int x, int y, char* z) { std::cout << "::f1(int,int,char*)\n"; }
#define GENERATE_ARG(z,n,unused) BOOST_PP_CAT(arg,n)
#define GET_ARGS(n) BOOST_PP_ENUM(n, GENERATE_ARG, ~)
#define GENERATE_PARAM(z,n,seq) BOOST_PP_SEQ_ELEM(n,seq) GENERATE_ARG(z,n,~)
#define GENERATE_PARAMS(seq) BOOST_PP_ENUM( BOOST_PP_SEQ_SIZE(seq), GENERATE_PARAM, seq )
#define PASSTHROUGH(Classname, Function, ArgTypeSeq) \
void Classname::Function( GENERATE_PARAMS(ArgTypeSeq) ) \
{ \
::Function( GET_ARGS( BOOST_PP_SEQ_SIZE(ArgTypeSeq) ) ); \
}
struct test
{
void f1(int,int,char*);
};
PASSTHROUGH(test,f1,(int)(int)(char*))
int main()
{
test().f1(5,5,0);
std::cin.get();
}
You could get something closer to yours if you use tuples, but you'd have to supply the arg count to the base function (you can't derive a size from a tuple). Sort of like so:
PASSTHROUGH(test,f1,3,(int,int,char*))
That about what you're looking for? I knew it could be done; took about a half hour to solve. You seem to expect that there's an implicit 'this' that has to be gotten rid of but I don't see why...so maybe I misunderstand the problem. At any rate, this will let you quickly make default "passthrough" member functions that defer to some global function. You'll need a DECPASSTHROUGH for the class declaration if you want to skip having to declare them all...or you could modify this to make inline functions.
Hint: Use BOOST_PP_STRINGIZE((XX)) to test the output of preprocessor metafunctions.
My initial thought, and this probably won't work or others would have stated this, is to put all your base functions together in a class as virtual. Then, write the functionality improvements into inherited classes and run with it. It's not a macro wrapper, but you could always call the global functions in the virtual classes.
With some assembly trickery, you could probably do exactly what you'd want, but you would lose portability more than likely. Interesting question and I want to hear other's answers as well.
You may want to use a namespace if you want to not deal with class stuff, like this. You could also use static member methods in a class, but I think that people don't like that anymore.
#ifndef __cplusplus
#define PASSTHRU(type, prefix, func, args) type prefix##_##func args
#else
#define PASSTHRU(type, prefix, func, args) type prefix::func args
#endif
Or
#ifndef __cplusplus
#define PASSTHRU(type, prefix, func, ...) type prefix##_##func(__VA_ARGS__)
...
Perfect forwarding relies on rvalue references. STL has a blog entry on it at Link and you would want to choose a compiler that supported the feature to take this approach. He's discussing Visual C++ 2010.

Looking for the most elegant code dispatcher

I think the problem is pretty common. You have some input string, and have to call a function depending on the content of the string. Something like a switch() for strings.
Think of command line options.
Currently I am using:
using std::string;
void Myclass::dispatch(string cmd, string args) {
if (cmd == "foo")
cmd_foo(args);
else if (cmd == "bar")
cmd_bar(args);
else if ...
...
else
cmd_default(args);
}
void Myclass::cmd_foo(string args) {
...
}
void Myclass::cmd_bar(string args) {
...
}
and in the header
class Myclass {
void cmd_bar(string args);
void cmd_foo(string args);
}
So every foo and bar I have to repeat four (4!) times. I know I can feed the function pointers and strings to an static array before and do the dispatching in a loop, saving some if...else lines. But is there some macro trickery (or preprocessor abuse, depending on the POV), which makes is possible to somehow define the function and at the same time have it update the array automagically?
So I would have to write it only twice, or possibly once if used inline?
I am looking for a solution in C or C++.
It sounds like you're looking for the Command pattern
Something like this:
Create a map like this
std::map<std::string, Command*> myMap;
then just use your key to execute the command like this....
std::map<std::string, Command*>::iterator it = myMap.find(str);
if( it != myMap.end() ) {
it->second->execute()
}
To register your commands you just do this
myMap["foo"] = new CommandFoo("someArgument");
myMap["bar"] = new CommandBar("anotherArgument");
The basic solution, per my link in the question comment, is to map a string to a function call of some sort.
To actually register the string -> function pointer/functor pair:
Firstly, have a singleton (shock! horror!) dispatcher object.
Let's call it TheDispatcher - it's a wrapper for a map<string,Func>, where
Func is your function pointer or functor type.
Then, have a register class:
struct Register {
Register( comst string & s, Func f ) {
TheDispatcher.Add( s, f );
}
};
Now in your individual compilation units you create
static objects (shock! horror!):
Register r1_( "hello", DoSayHello );
These objects will be created (assuming the code is not in a static library) and will automatically register with TheDispatcher.
And at run-time, you look up strings in TheDispatcher and execute the associated function/functor.
as alternative to the Command pattern you can build an hashtable of string -> function pointers:
typedef void (*cmd)(string);
The ugly macro solution, which you kind-of asked for. Note that it doesn't automatically register, but it does keep some things synchronized, and also will cause compile errors if you only add to mappings, and not the function in the source file.
Mappings.h:
// Note: no fileguard
// The first is the text string of the command,
// the second is the function to be called,
// the third is the description.
UGLY_SUCKER( "foo", cmd_foo, "Utilize foo." );
UGLY_SUCKER( "bar", cmd_bar, "Turn on bar." );
Parser.h:
class Myclass {
...
protected:
// The command functions
#define UGLY_SUCKER( a, b, c ) void b( args )
#include Mappings.h
#undef UGLY_SUCKER
};
Parser.cpp:
void Myclass::dispatch(string cmd, string args) {
if (cmd == "")
// handle empty case
#define UGLY_SUCKER( a, b, c ) else if (cmd == a) b( args )
#include Mappings.h
#undef UGLY_SUCKER
else
cmd_default(args);
}
void Myclass::printOptions() {
#define UGLY_SUCKER( a, b, c ) std::cout << a << \t << c << std::endl
#include Mappings.h
#undef UGLY_SUCKER
}
void Myclass::cmd_foo(string args) {
...
}
You'll have to at least define the functions and add them to some registry. (If they are to be non-inline member functions of some class, you'll also have to declare them.) Other than some domain-specific language generating the actual code (like cjhuitt's macro hackery), I see no way around mentioning these functions two (or three) times.