member function alternative names - c++

I am trying to create alternative names for the function call numberedFunction when it has certain values as below
template< typename T >
class X
{
public:
X() : single( std::bind( &X::numberedFunction, *this, 1 ) ),
halfDozen( std::bind( &X::numberedFunction, *this, 6 ) )
{ ... }
T numberedFunction( unsigned int i ) { ... }
const std::function< T() >& single;
const std::function< T() >& halfDozen;
};
But this code is not correct (segfaults when I try to use any of the specially named functions). Is there an issue with using this the way I am in the initialization list (e.g., is this not guarenteed to be well-formed at the time I am accessing it there)? Something else (obvious)? Is there a better way to do what I am trying to do (I feel like there almost definitely is)?

const std::function< T() >& single;
const std::function< T() >& halfDozen;
Your members are references to const, but you are initializing them from a temporary in the constructor (assuming the bind expressions in your real code aren't nonsensical). As soon as the construction is done they are invalid. Is this really what you intended?
Maybe this is what you want do do (using psychic powers here):
template< typename T >
class X
{
public:
X() : single( std::bind( &X::numberedFunction, this, 1 ) ),
halfDozen( std::bind( &X::numberedFunction, this, 6 ) )
{ ... }
T numberedFunction( unsigned int i ) { ... }
const std::function< T() > single;
const std::function< T() > halfDozen;
};
Notice that I'm binding to this, not *this. This avoids a copy, but may not be what you want.

An alternative approach is to just add a few forwarding functions:
T numberedFunction( unsigned int i ) { ... }
T single()
{ return numberedFunction(1); }
T halfDozen()
{ return numberedFunction(6); }

You're using this pointer in the initialization list. It's an uninitialized object. I wonder whether you could compile this code successfully or not!
See a sample to see the usage of bind (taken from MSDN)
// std_tr1__functional__bind.cpp
// compile with: /EHsc
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std::placeholders;
void square(double x)
{
std::cout << x << "^2 == " << x * x << std::endl;
}
void product(double x, double y)
{
std::cout << x << "*" << y << " == " << x * y << std::endl;
}
int main()
{
double arg[] = {1, 2, 3};
std::for_each(&arg[0], arg + 3, square);
std::cout << std::endl;
std::for_each(&arg[0], arg + 3, std::bind(product, _1, 2));
std::cout << std::endl;
std::for_each(&arg[0], arg + 3, std::bind(square, _1));
return (0);
}

Related

Passing reference_wrapper objects as function arguments in C++11

How does one pass and operate on constant (or non constant) references inside STL containers. Say I have a function:
bool foo(const Obj& A, const Obj& B) {
// do some computation on A & B
}
and since A & B always occur together, I would like to put them in an STL pair:
bool foo(const std::pair<Obj, Obj>& A_and_B) {
// do some computation on A & B
}
However now both objects A & B get copied into a pair every time foo needs to be called. Looking around I found reference_wrapper in C++11. Though doing something like this doesn't quite work:
bool foo(const std::pair<std::reference_wrapper<Obj>, std::reference_wrapper<Obj>>& A_and_B) {
// do some computation on A & B
}
bool foo(const std::pair<Obj, Obj>& A_and_B) {
foo(std::make_pair(std::ref(A_and_B.first), std::ref(A_and_B.second)));
}
What is the correct way of passing containers with reference values without using pointers?
To avoid copy when make_pair, why not define the pair as std::pair<Obj&, Obj&> directly?
#include <iostream>
#include <string>
#include <functional>
class Obj
{
};
bool foo(const std::pair<Obj, Obj>& A_and_B) {
// do some computation on A & B
std::cout << __func__ << std::endl;
}
bool foo(const std::pair<Obj&, Obj&>& A_and_B) {
// do some computation on A & B
std::cout << "ref version foo" << std::endl;
}
int main( void )
{
Obj A;
Obj B;
foo( std::make_pair(std::ref(A), std::ref(B)) );
return 0;
}
Here's one way, passing just a pair of references (no copying):
#include <utility> // pair
#include <functional> // ref
#include <iostream>
using namespace std;
struct Obj {};
auto foo( pair<Obj const&, Obj const&> const ab )
{
Obj const& a = ab.first;
Obj const& b = ab.second;
cout << &a << " " << &b << endl;
}
auto main() -> int
{
Obj a;
Obj b;
cout << &a << " " << &b << endl;
foo( make_pair( ref( a ), ref( b ) ) );
}
This works nicely because std::make_pair has special support for std::reference_wrapper arguments, then deducing reference to the referred to type.
std::reference_wrapper is the result type of std::ref.
Since std::make_pair supports move semantics, you just need to write your function as you suggested, but when calling it move objects A and B into the std::make_pair as shown below:
// Just as you already suggested
bool foo(const std::pair<Obj, Obj>& A_and_B) {
// do some computation on A & B
}
Call it as:
int main( void )
{
Obj A; // work on A
Obj B; // work on B
auto A_and_B = std::make_pair(std::move(A), std::move(B)); // effectively moves A and B; no copies!
// A and B are now reset, but you can use A_and_B.first and A_and_B.second!
foo( A_and_B );
return 0;
}
Live demo.
Since you are passing the pair by reference, it is not copied. However, Obj A=A_and_B.first will create a copy. If you want to avoid that, you can get a reference to the element, i.e.
Obj &A=A_and_B.first.

unique_ptr and default constructible pointer

Recently I tried to reinvent scope guard via std::unique_ptr (NOTE: Deleter has the member typedef pointer — is a specially handled case of std::unique_ptr):
#include <type_traits>
#include <utility>
#include <memory>
#include <iostream>
#include <cstdlib>
#include <cassert>
namespace
{
template< typename lambda >
auto
make_scope_guard(lambda && _lambda)
{
struct lambda_caller
{
using pointer = std::decay_t< lambda >;
void
operator () (lambda & l) const noexcept
{
std::forward< lambda >(l)();
}
};
return std::unique_ptr< std::decay_t< lambda >, lambda_caller >(std::forward< lambda >(_lambda));
}
}
int
main()
{
std::cout << 1 << std::endl;
{
std::cout << 2 << std::endl;
[[gnu::unused]] auto && guard_ = make_scope_guard([&] { std::cout << __PRETTY_FUNCTION__ << std::endl; });
std::cout << 3 << std::endl;
}
std::cout << 5 << std::endl;
return EXIT_SUCCESS;
}
Such an approach works fine for simple pointer to free function void f() { std::cout << 4 << std::endl; } passed to make_scope_guard, but not for any lambda passed to make_scope_guard.
This is due to an abundance of ... = pointer() into the std::unique_ptr definition (function default parameter, defaulting data memebers etc), but I can't find the DefaultConstructible requirement for pointer into this article.
Is it mandatory, that the pointer should match the std::is_default_constructible requirement?
It tested against libc++ and against libstdc++ using not too old clang++ -std=gnu++1z.
Seems, there should be language extension for lambdas: if auto l = [/* possible capture list */] (Args...) { /* code */; }; then using L = decltype(l); is equivalent to struct L { constexpr void operator () (Args...) const noexcept { ; } }; for some Args..., isn't it?
ADDITIONAL:
Providing the instance D{} of following DefaultConstructible class to make_scope_guard(D{}) requires commented out code to be uncommented in the context if (p) { ..., where p is of type D:
struct D { void operator () () const noexcept { std::cout << __PRETTY_FUNCTION__ << std::endl; } /* constexpr operator bool () const { return true; } */ };
A unique_ptr is still a pointer. You cannot shoehorn a lambda into it. From [unique.ptr]:
A unique pointer is an object that owns another object and manages that other object through a pointer.
More precisely, a unique pointer is an object u that stores a pointer to a second object p and will dispose of
p when u is itself destroyed
[...]
Additionally, u can, upon request, transfer ownership to another unique pointer u2. Upon completion of
such a transfer, the following post-conditions hold: [...] u.p is equal to nullptr
A lambda is not a pointer. A lambda cannot equal nullptr.
That said, you're already making your own local struct, why not just use that to do the RAII scope guarding itself instead of deferring to unique_ptr? That seems like a hack at best, and takes more code to boot. You could instead just do:
template< typename lambda >
auto
make_scope_guard(lambda && _lambda)
{
struct lambda_caller
{
lambda _lambda;
~lambda_caller()
{
_lambda();
}
};
return lambda_caller{std::forward<lambda>(_lambda)};
}
If you need to support release, you can wrap _lambda inside of boost::optional so that lambda_caller becomes:
struct lambda_caller
{
boost::optional<lambda> _lambda;
~lambda_caller()
{
if (_lambda) {
(*_lambda)();
_lambda = boost::none;
}
}
void release() {
_lambda = boost::none;
}
};

how do we pass an arbitrary function to another function

I have a question continuing the post Function passed as template argument. In the provided code:
#include <iostream>
void add1(int &v)
{
v+=1;
}
void add2(int &v)
{
v+=2;
}
template <void (*T)(int &)>
void doOperation()
{
int temp=0;
T(temp);
std::cout << "Result is " << temp << std::endl;
}
int main()
{
doOperation<add1>();
doOperation<add2>();
}
what about a third function which has a different parameter set layout, e.g.
double add3(double v1, double v2)
{
return v1+v2;
}
If this is not achievable using template at all, how do we pass an arbitrary function to another function? And how do we handle the parameter set with all kinds of possibilities? I know python may be able to do it by passing a tuple (kwargs**), but not sure about C/C++.
One form of passing a generic function to be called is a callable templated type:
#include <functional>
#include <iostream>
template<typename F>
void callFoo(F f) {
f();
}
int main() {
callFoo(std::bind([](int a, int b) {std::cout << a << ' ' << b;}, 5, 6));
}
callFoo takes a callable type, F, and calls it. Around this call, you can, for example, do timer work to time the function. In main, it's called with a lambda that has two parameters and the values given to those parameters bound to it. callFoo can then call it without storing the arguments. This is very similar to taking a parameter with the type std::function<void()>.
If, however, you don't want to use std::bind, you can pass in the arguments separately with a couple changes:
template<typename F, typename... Args>
void callFoo(F f, Args... args) { //ignoring perfect forwarding
f(args...);
}
int main() {
callFoo(/*lambda*/, 5, 6);
}
In these cases, passing void functions makes sense. Indeed, return values can be used as parameters and passed in with std::ref. If you plan on returning what the function returns, you'll have to handle the special case of the return type being void, as you can't assign to a void variable and return that. At this point, it's easier to direct you to my previous question on the matter. My use case for it turned out to be moot, but the solution works great for other uses.
This could possibly lead you closer to what you want:
#include <iostream>
void add1(int &v)
{
v+=1;
}
double add2(double v1, double v2)
{
return v1 + v2;
}
// 1 param version
template< class aRetType, class tP1 >
aRetType doOperation( aRetType (*aFunction)( tP1 aP1 ), tP1 valP1 )
{
return aFunction( valP1 );
}
// 2 param version
template< class aRetType, class tP1, class tP2 >
aRetType doOperation( aRetType (*aFunction)( tP1 aP1, tP2 aP2 ), tP1 valP1, tP2 valP2 )
{
return aFunction( valP1, valP2 );
}
// 3 param version and up is not given, but you get the trick.
int main()
{
int iTemp = 8;
doOperation< void, int& >( add1, iTemp );
std::cout << "Result is " << iTemp << std::endl;
double iResult;
iResult = doOperation< double, double, double >( add2, 2.2, 8.8);
std::cout << "Result is " << iResult << std::endl;
}

Is it possible to pass a pointer-to-class-member as an single argument in C++?

Here is well described how to call member function by pointer:
http://www.newty.de/fpt/functor.html
But the functor needs to get 2 arguments: pointer-to-object and pointer-to-member-function:
TSpecificFunctor(TClass* _pt2Object, void(TClass::*_fpt)(const char*))
{ pt2Object = _pt2Object; fpt=_fpt; }
call:
(*pt2Object.*fpt)(string);
Is it possible to pass single argument like C-style:
func() -- call
func -- function pointer
Why obj.method isn't complete pointer-to-class-member?
The syntax object.*ptmf doesn't create an intermediate object. It has no meaning and is forbidden by the language. You have to immediately call the result of accessing a pointer to member function.
You can explicitly create such an object using std::bind, which interprets the ptmf as a functor object, and makes the implicit this argument explicit.
auto fn = std::bind( ptmf, object, std::placeholders::_1 );
std::function< void( const char * ) > stdfn = fn;
fn( "foo" ); // equivalent to object.*ptmf( "foo" );
http://ideone.com/ds24F
Note that this functionality is new in C++11. Although C++03 TR1 has function and bind, they won't perform this conversion on a ptmf. (Plain C++03 can do the job with std::mem_fn and std::bind1st, but they are extremely painful to use and have been deprecated.)
Ask yourself if it is possible to call member method without specifying an object.
Consider this:
class A {
public: void m() {}
};
int main() {
m(); // can't call without object - like: A a; a.m();
}
Is it possible to pass a pointer-to-class-member as an single argument in C++?
No, it is not possible. You need the object of the class on which you want to call the method.
You can go around this by using lambda functions, like in next example :
#include <iostream>
#include <functional>
void call( const std::function< void( const char * a ) > & fn )
{
fn("hi");
}
void foo( const char * a )
{
std::cout << "foo : " << a << std::endl;
}
class bar
{
public:
void operator()( const char * a )
{
std::cout << "bar : " << a << std::endl;
}
};
int main()
{
bar b;
const auto f1 = [&]( const char * a ){ b(a); };
const auto f2 = foo;
call( f1 );
call( f2 );
}

C++: How do I pass a function(without knowing its parameters) to another function?

I'm trying to create a function that will store and repeat another function given as a parameter for a specific amount of time or repeats given.
But when you want to pass a function as a parameter you have to know all of its parameters before hand.
How would I do if I wanted to pass the function as one parameter, and the parameters as another?
void AddTimer(float time, int repeats, void (*func), params); // I know params has no type and that (*func) is missing parameters but it is just to show you what I mean
Thanks in advance
The best that you can do is use std::function or boost::function as argument, together with std::bind or boost::bind to, well, bind the arguments with the function:
void foo() { std::cout << "foo" << std::endl; }
void bar( int x ) { std::cout << "bar(" << x << ")" << std::endl; }
struct test {
void foo() { std::cout << "test::foo" << std::endl; }
};
void call( int times, boost::function< void() > f )
{
for ( int i = 0; i < times; ++i )
f();
}
int main() {
call( 1, &foo ); // no need to bind any argument
call( 2, boost::bind( &bar, 5 ) );
test t;
call( 1, boost::bind( &test::foo, &t ) ); // note the &t
}
Note that there is something inherently wrong with passing a fully generic function pointer: how do you use it? How would the body of the calling function look like to be able to pass an undefined number of arguments of unknown types? That is what the bind templates resolve, they create a class functor that stores the function pointer (concrete function pointer) together with copies of the arguments to use when calling (note the &t in the example so that the pointer and not the object is copied). The result of the bind is a functor that can be called through a known interface, in this case it can be bound inside a function< void() > and called with no arguments.
dribeas' answer is correct as far as modern C++ is concerned.
For the sake of interest, there's also a simple lo-tech solution from the C world that as far as it goes, works in C++. Instead of allowing arbitrary parameters, define the function as void (*func)(void*), and make "params" void*. It's then the caller's job to define some struct that will contain the parameters, and manage its lifecycle. Usually the caller would also write a simple wrapper to the function that's really needed to be called:
void myfunc(int, float); // defined elsewhere
typedef struct {
int foo;
float bar;
} myfunc_params;
void myfunc_wrapper(void *p) {
myfunc_params *params = (myfunc_params *)p;
myfunc(params->foo, params->bar);
}
int main() {
myfunc_params x = {1, 2};
AddTimer(23, 5, myfunc_wrapper, &x);
sleep(23*5 + 1);
}
In practice you want to "fire and forget" timers, so if you use this scheme you may also need a way for the timer manage to free the userdata pointer once all firings have completed.
Obviously this has limited type safety. In principle in shouldn't matter, because whoever supplies the function pointer and user data pointer shouldn't have a great deal of difficulty ensuring that they match. In practice of course people find ways to write bugs, and ways to blame you because their compiler didn't tell them about the bugs ;-)
It's just an example how you could pass function pointer to another function, and then call it:
void AddTimer(float time, int repeats, void (*func)(int), int params)
{
//call the func
func(params);
}
void myfunction(int param)
{
//...
}
AddTimer(1000.0, 10, myfunction, 10);
Similarly, you can write your code if your function takes different type or/and numbers of parameters!
If there's really no rules about the function pointer at all, just use void*.
In C++11, things get really simple - you get everything you need to implement your timers.
The most concise way of passing bound function calls is by passing a functor generated using lambda syntax, e.g.: []{ std::cout << "Hello, world!" << std::endl; }. An object thus generated has a type known only to the compiler, but the type is convertible to std::function<void()>.
#include <functional>
#include <list>
#include <chrono>
#include <thread>
#include <iostream>
template <typename Clock = std::chrono::high_resolution_clock>
class Timers {
public:
using clock = Clock;
using duration = typename clock::duration;
using time_point = typename clock::time_point;
private:
struct Timer {
duration const period;
std::function<void()> const call;
int repeats;
time_point next;
Timer(duration $period, int $repeats, std::function<void()> && $call) :
period($period), call(std::move($call)), repeats($repeats) {}
};
std::list<Timer> m_timers;
public:
Timers() {}
Timers(const Timers &) = delete;
Timers & operator=(const Timers &) = delete;
template <typename C> void add(std::chrono::milliseconds period,
int repeats, C && callable)
{
if (repeats) m_timers.push_back(Timer(period, repeats, callable));
}
enum class Missed { Skip, Emit };
void run(Missed missed = Missed::Emit) {
for (auto & timer : m_timers) timer.next = clock::now() + timer.period;
while (! m_timers.empty()) {
auto next = time_point::max();
auto ti = std::begin(m_timers);
while (ti != std::end(m_timers)) {
while (ti->next <= clock::now()) {
ti->call();
if (--ti->repeats <= 0) {
ti = m_timers.erase(ti);
continue;
}
do {
ti->next += ti->period;
} while (missed == Missed::Skip && ti->next <= clock::now());
}
next = std::min(next, ti->next);
++ ti;
}
if (! m_timers.empty()) std::this_thread::sleep_until(next);
}
}
};
int main(void)
{
Timers<> timers;
using ms = std::chrono::milliseconds;
timers.add(ms(1000), 2, []{ std::cout << "Hello, world!" << std::endl; });
timers.add(ms(100), 20, []{ std::cout << "*" << std::endl; });
timers.run();
std::cout << std::endl;
return 0;
}