It's easy to create a new name for a type, a variable or a namespace. But how do I assign a new name to a function? For example, I want to use the name holler for printf. #define is obvious... any other way?
Solutions:
#define holler printf
void (*p)() = fn; //function pointer
void (&r)() = fn; //function reference
inline void g(){ f(); }
There are different approaches:
With C++11 with non-template non-overloaded functions you can simply use:
const auto& new_fn_name = old_fn_name;
If this function has multiple overloads you should use static_cast:
const auto& new_fn_name = static_cast<OVERLOADED_FN_TYPE>(old_fn_name);
Example: there are two overloads of function std::stoi
int stoi (const string&, size_t*, int);
int stoi (const wstring&, size_t*, int);
If you want to make an alias to the first version you should use the following:
const auto& new_fn_name = static_cast<int(*)(const string&, size_t*, int)>(std::stoi);
Note: there is no way to make an alias to overloaded function such that all its overloaded versions work, so you should always specify which exact function overload you want.
With C++14 you can go even further with constexpr template variables. That allows you to alias templated functions:
template<typename T>
constexpr void old_function(/* args */);
template<typename T>
constexpr auto alias_to_old = old_function<T>;
Moreover, starting with C++11 you have a function called std::mem_fn that allows to alias member functions. See the following example:
struct A {
void f(int i) {
std::cout << "Argument: " << i << '\n';
}
};
A a;
auto greet = std::mem_fn(&A::f); // alias to member function
// prints "Argument: 5"
greet(a, 5); // you should provide an object each time you use this alias
// if you want to bind an object permanently use `std::bind`
greet_a = std::bind(greet, a, std::placeholders::_1);
greet_a(3); // equivalent to greet(a, 3) => a.f(3);
You can create a function pointer or a function reference:
void fn()
{
}
//...
void (*p)() = fn;//function pointer
void (&r)() = fn;//function reference
typedef int (*printf_alias)(const char*, ...);
printf_alias holler = std::printf;
Should do you fine.
int (*holler)(const char*, ...) = std::printf;
Use an inline wrapper. You get both APIs, but keep the single implementation.
With C++14 generic lambdas, I was able to do the following, which should also work when the target function has multiple overloads:
constexpr auto holler = [] ( auto &&...args ) {
return printf( std::forward<decltype(args)>( args )... );
};
From fluentcpp : ALIAS_TEMPLATE_FUNCTION(f, g)
#define ALIAS_TEMPLATE_FUNCTION(highLevelF, lowLevelF) \
template<typename... Args> \
inline auto highLevelF(Args&&... args) -> decltype(lowLevelF(std::forward<Args>(args)...)) \
{ \
return lowLevelF(std::forward<Args>(args)...); \
}
It is worth mentioning here IMO that while the original question (and great answers) are definitely useful if you want to rename a function (there are good reasons to do so!), if all you want to do is strip out a deep namespace but keep the name, there is the using keyword for this:
namespace deep {
namespace naming {
namespace convention {
void myFunction(int a, char b) {}
}
}
}
int main(void){
// A pain to write it all out every time
deep::naming::convention::myFunction(5, 'c');
// Using keyword can be done this way
using deep::naming::convention::myFunction;
myFunction(5, 'c'); // Same as above
}
This also has the advantage of it being confined to a scope, though you could always use it at the top level of a file. I often use this for cout and endl so I don't need to bring in ALL of std with the classic using namespace std; at the top of a file, but also useful if you're using something like std::this_thread::sleep_for() a lot in one file or function, but not everywhere, and not any other functions from the namespace. As always, it's discouraged to use it in .h files, or you'll pollute the global namespace.
This is not the same as the "renaming" above, but is often what is really wanted.
Related
I would like to generate a function that forwards its arguments to another function. I know that std::function does it somehow, but I cannot seem to find the right syntax myself.
It would be ok for my usecase to use som kind of template magic, but i want
the user to be able to get information on the calling types when they use the function, like std::function does.
My usecase uses class member functions, so a solution that only works in that context is accepted. I tried to created the smallest example code possible.
#include <iostream>
// Macro usage cannot be changed
#define ARGS int, int
void otherFunction(int x, int y) {
std::cout << x << "," << y << "\n";
}
// This is the behaviour i want
void expectedImplementation(int _1, int _2) {
otherFunction(_1, _2);
}
// This works, but it prevents the user to view the expected
// types in their IDE
template <typename ...Args>
void templateVersion(Args ... args) {
otherFunction(args...);
}
// This is the version I cannot get to work
// It does not need to look like this, but it needs to get
// its argument types from
//void func(ARGS) {
// otherFunction(/*how?*/);
//}
int main() {
expectedImplementation(1, 2);
templateVersion(1, 2);
//func(1, 2);
}
godbolt
How do I accomplish this?
Edit:
The function that needs to be forwarded to is also different for each instance of the function.
Edit 2:
Ok, It seems like it's hard to specify the context without the context. Here is the actual code that I want to generalize. Here Is the template magick stuff where it should fit in. No memory should be used, otherwise I would just use the solution I have now with template parameter packs.
Edit 3:
A better example:
#include <iostream>
#define ARGS int, int
struct Inner {
void otherFunction(int x, int y) {
std::cout << x << y << std::endl;
}
};
struct Wrapper {
Inner inner;
// This works, but it prevents the user to view the expected
// types in their ide
template <typename ...Args>
void templateVersion(Args ... args) {
inner.otherFunction(args...);
}
// The concept I try to figure out
void function(ARGS) { // It does not need to look exactly like this
// , but functionally it needs to be somithing like it
// Forward the arguments to the `ìnner` class
}
};
int main() {
auto wrapper = Wrapper{};
wrapper.templateVersion(10, 20);
}
Your macro ARGS does not define named arguments. You cannot forward the type of unnamed arguments. That's a limitation of the language.
Either forget about using macros, and change your function definiton:
void func(int a, int b) {
otherFunction(a, b);
}
Or change the definition of the macro:
#define ARGS int a, int b
void func(ARGS) {
otherFunction(a, b);
}
That said, nothing beats the template solution. Make sure you use perfect forwarding.
template <typename ...Args>
void templateVersion(Args&& ... args) {
otherFunction(std::forward<Args>(args)...);
}
The standard way to represent a pointer to a member function for a specific instance of a class is to use a pointer to the instance and a pointer to the member function:
void Execute(Foo* inst, void (Foo::*func)(int), int x) {
(inst->*func)(x);
}
...
Execute(foo, &Foo::Bar, 42);
Is there any way to define Execute such that the function pointer is represented as a single expression?
For example:
void Execute(SomeType v, int x) {
(v.inst->*v.func)(x);
}
...
Execute(foo->Bar, 42);
My main problem is that in my specific case, Foo is nested under a long and unstable chain of namespaces, so an actual invocation using the standard syntax looks more like Execute(foo, &hello::darkness::my::old::friend::Foo::Bar, 42). I almost always have a local foo instance however, from which I can refer to the much simpler foo->Bar(42). I need to do some extra bookkeeping though, which is why I need to wrap the call in something like Execute. using directives and namespace aliases are not an option unfortunately.
Is there any way to define Execute such that the function pointer is represented as a single expression?
Yes. Change the function to use std::function or a callable template parameter, eg:
#include <functional>
void Execute(std::function<void(int)> v, int x)
{
v(x);
}
template<typename Callable>
void Execute(Callable v, int x)
{
v(x);
}
And then you can use std::bind() or a lambda for the input expression, eg:
#include <functional>
using namespace std::placeholders;
using FooType = std::remove_reference<decltype(*foo)>::type;
Execute(std::bind(&FooType::Bar, foo, _1), 42);
// or, in C++20 and later:
Execute(std::bind_front(&FooType::Bar, foo), 42);
Execute([=](int x){ foo->Bar(x); }, 42);
Also, just to mention that in C++Builder specifically, there is a __closure extension that allows calling member methods without having to qualify the class type at all, eg:
typedef void (__closure *TExecuteCallable)(int);
void Execute(TExecuteCallable v, int x)
{
v(x);
}
...
Execute(foo->Bar, 42);
// or
Execute(&(foo->Bar), 42);
I have a template function, let's call it the "client":
template<typename T>
void client(T (*func)(const std::string&), const std::string& s) {}
Then there are a number of "adaptee" functions that all have an identical type of the first, non-default argument, but the following arguments vary in number and have default values:
void adaptee_one(const std::string&, int i = 1, char* c = nullptr) {}
void adaptee_two(const std::string&, float* f = nullptr) {}
The above functions are a given. Now what I want to do is to pass them to the above client<>() function as the first parameter, and I only care about passing the first argument, const std::string&. So I do the following:
void bindAdapteeOne(const std::string& s) {
return adaptee_one(s);
}
void bindAdapteeTwo(const std::string& s) {
return adaptee_two(s);
}
And then pass bindAdapteeX() to client<>().
What I'd like to do is to automate the wrapping or have one (templated) wrapper instead of one per adaptee. I feel this might be the case for variadics, but have little idea about how to apply them exactly.
C++11 is fine, C++14 is fine if absolutely necessary.
C++11 is fine, C++14 is fine if absolutely necessary.
C++11 solution here.
What I'd like to do is to automate the wrapping or have one (templated) wrapper instead of one per adaptee.
I wouldn't do that. You can simply use non-capturing lambdas and let them decay to function pointers:
client (+[](const std::string& s) { return adaptee_one(s); }, "foo");
I don't think that wrapping them in template stuff or whatever would give you a solution that is more readable or easy to use.
As a minimal, working example:
#include<string>
template<typename T>
void client(T (*func)(const std::string&), const std::string& s) {}
void adaptee_one(const std::string&, int i = 1, char* c = nullptr) {}
void adaptee_two(const std::string&, float* f = nullptr) {}
int main() {
client (+[](const std::string& s) { return adaptee_one(s); }, "foo");
}
This is one of those times where a macro helps:
#define WRAP_FN(f) +[](std::string const& s) -> decltype(auto) { return f(s); }
Though you could just write the body of that inline instead.
There isn't anything else you could do. The problem is that the default arguments aren't visible in the function's signature, so once you get into the type system, there's no way to differentiate:
void works(std::string const&, int=0);
void fails(std::string const&, int );
Both of those are void(*)(std::string const&, int). So you can't have a function template or class template wrapper - you need to do it inline with a lambda (or a macro that wraps a lambda).
I'm thinking I would create a class that wraps your parameters and have the client accept an instance of that class. That way, you only have one parameter, which contains however many parameters you so desire.
That parameter wrapper would provide the default values as well, and allow you to refine them in derived classes for specific purposes.
This is probably a little more self-documenting as well when compared to lambdas.
And who knows, when its time to read and write the parameters from a file, then the wrapper class would be the perfect place to do it.
In the following toy-example, I would like to get the name of a function. The function itself was given as an std::function argument. Is it possible in C++ to get name of a std::function object?
void printName(std::function<void()> func){
//Need a function name()
std::cout << func.name();
}
void magic(){};
//somewhere in the code
printName(magic());
output: magic
Otherwise I would have to give the function's name as a second parameter.
No there isn't. Function names (like variable names) are compiled out so they are not visible at run-time.
Your best bet is to pass the name of the function (use a std::string or a const char*) as you've suggested yourself. (Alternatively you could base a solution on __func__ which was introduced in C++11.)
The answer is no, but you could make something like
template<class R, class... Args>
class NamedFunction
{
public:
std::string name;
std::function<R(Args...)> func;
NamedFunction(std::string pname, std::function<R(Args...)> pfunc) : name(pname), func(pfunc)
{}
R operator()(Args&&... a)
{
return func(std::forward<Args>(a)...);
}
};
And then define a preprocessor
#define NAMED_FUNCTION(var, type, x) NamedFunction<type> var(#x,x)
...
NAMED_FUNCTION(f, void(), magic);
Given a std::function it has a member function called target_type which returns the typeid of the stored function object. That means you can do
void printName(std::function<void()> func){
//Need a function name()
std::cout << func.target_type().name();
}
This returns an implementation-defined string that is unique for each type. With Visual Studio, this string is human-readable already. With gcc (or maybe it's glibc? I don't know who takes care of what in detail) you need to use abi::__cxa_demangle after including <cxxabi.h> to get a human-readable version of the type name.
EDIT
As Matthieu M. pointed out, given a function pointer, the type returned by this will just be the function's signature. For example:
int function(){return 0;}
printName(function);
This will output (assuming you demangled if necessary) int (*)() which is not the function's name.
This method will work with classes though:
struct Function
{
int operator()(){return 0;}
};
printName(Function{});
This will print Function as desired, but then doesn't work for function pointers.
You could also have your function with a string parameter for the name and then use a macro to call it
void _printName(std::function<void()> func, const std::string& funcName){
std::cout << funcName;
}
#define printName(f) _printName(f, #f)
void magic(){};
//somewhere in the code
printName(magic);
See example
Maintain your own map from function pointer to name.
template<class Sig>
std::map<Sig*, const char*>& name_map() {
static std::map<Sig*, const char*> r;
return r;
}
struct register_name_t {
template<class Sig>
register_name_t( Sig* sig, const char* name ) {
name_map()[sig]=name;
}
};
#define TO_STRING(A) #A
#define REGISTER_NAME(FUNC) \
register_name_t FUNC ## _register_helper_() { \
static register_name_t _{ FUNC, TO_STRING(FUNC) }; \
return _; \
} \
static auto FUNC ## _registered_ = FUNC ## _register_helper_()
Simply do REGISTER_NAME(magic); to register the name magic to the function magic. This should be done at file scope, either in a header or a cpp file.
Now we check if the std::function has a function pointer matching its signature stored inside of it. If so, we look it up in our name_map, and return the name if we find it:
template<class Sig>
std::string get_function_name( std::function<Sig> const& f ) {
auto* ptr = f.target<Sig*>();
if (!ptr) return {};
auto it = name_map().find(ptr);
if (it == name_map().end()) return {};
return it->second;
}
this is generally a bad idea.
I think the simplest solution is to use typeid(fun).name() for example like this:
#include <typeinfo>
#include <stdio.h>
void foobar( void )
{
}
int main()
{
printf( "%s\n", typeid( foobar ).name() );
return 0;
}
Now, it have a lot of drawbacks, and I would not recommend using that.
First of all, IIRC it shows the symbol of the function, not the name you used in source code.
Also, the name will change from compiler to compiler.
And finally, RTTI is slow.
[edit]
Also, I'm not sure how it works with std::function. Never used that, honestly.
While reading some code, I came across this function. I have lots of trouble understanding the signature of the function. What are the things that I need to know before I can make head or tail of the following code?
I have been using C++ for a while now. I know what templates, function pointers are. However, I cannot make out what T::* might mean, what the line starting with _Defer means semantically.
Also, the first line of the function seems quite intimidating. Is there some resource that I can read up before trying to re-assess this code?
template <typename T>
_Defer<void(*(PID<T>, void (T::*)(void)))
(const PID<T>&, void (T::*)(void))>
defer(const PID<T>& pid, void (T::*method)(void))
{
void (*dispatch)(const PID<T>&, void (T::*)(void)) =
&process::template dispatch<T>;
return std::tr1::bind(dispatch, pid, method);
}
Source: https://github.com/3rdparty/libprocess/blob/master/include/process/defer.hpp
This might help clear things up a little:
template<typename T>
using VoidPMemberFn = void(T::*)(); // Pointer to member function of T
// that accepts no arguments and
// returns nothing.
template<typename T>
using DeferResultType = void (*)(const PID<T> &, VoidPMemberFn<T>);
template<typename T>
using DeferSignatureType = DeferResultType<T>(PID<T>, VoidPMemberFn<T>);
template<typename T>
_Defer<DeferSignatureType<T>> defer(const PID<T> &pid, VoidPMemberFn<T> method)
{
// Stuff...
}
EDIT
This might help clarify what the spaghetti in the _Defer template means, and how it relates to the above:
void(* (PID<T>, void (T::*)(void)) )(const PID<T>&, void (T::*)(void))
^-+^-^ ^-------------------------^ ^-------------+------------------^
| argument list |
| |
+-----------------------------------------------+
return type: void(*)(const PID<T> &, void(T::*)(void))
This creates a "signature", like those used with std::function (e.g. std::function<int(float)>).
More examples:
using sig = int(float);
sig gn; // Same as: "int gn(float)", a function declaration
int fn(float x)
{return (int)x;}
int main(int argc, char **argv)
{
// pointer to a function with signature "sig"
sig *pfn = &fn;
return 0;
}
int gn(float x)
{return (int)(x*x);}
This is non-standard non-portable code and hence hard to decode for humans. The return type
_Defer<void(*(PID<T>, void (T::*)(void)))(const PID<T>&, void (T::*)(void))>
is a specialisation of some class template _Defer defined in some header included. It is explained in defube's answer.
However, _Defer<> is not part of the std library specification and hence using it in this way makes the code non-portable and hence non-standard compliant. The same holds for the usage of std::tr1::bind instead of std::bind.
I guess your function's C++14 equivalent is simply
template <typename T>
auto defer(const PID<T>& pid, void (T::*method)())
{
auto dispatch = &process::template dispatch<T>;
return std::bind(dispatch, pid, method);
}
where process must be some class (or base class if defer is a member function) with static template member method dispatch. Thus, defer() returns some function object (see the documentation for std::bind) to be called later.
Note that the return type of std::bind is unspecified by the standard and hence auto (or packaging it into a std::function) the only portable way to handle it.