member function alternative names
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 ) 开发者_Python百科)
{ ... }
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);
}
精彩评论