成员函数备用名称

member function alternative names

本文关键字:备用 函数 成员      更新时间:2023-10-16

我正在尝试为函数调用numberedFunction创建替代名称,当它具有以下某些值时

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;
};

但是这段代码是不正确的(当我尝试使用任何特殊命名的函数时出现段错误(。 以我在初始化列表中的方式使用this是否存在问题(例如,在我在那里访问它时,这不能保证格式正确(? 别的东西(显而易见(? 有没有更好的方法来做我想做的事情(我觉得几乎肯定有(?

const std::function< T() >& single;
const std::function< T() >& halfDozen;

您的成员是对const的引用,但您正在从构造函数中的临时初始化它们(假设实际代码中的bind表达式不是无意义的(。一旦施工完成,它们就无效。这真的是你的意图吗?


也许这就是你想做的(在这里使用精神力量(:

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;
};

请注意,我绑定的是this,而不是*this。这样可以避免复制,但可能不是您想要的。

另一种方法是只添加一些转发函数:

T numberedFunction( unsigned int i ) { ... }
T single()
{ return numberedFunction(1); }
T halfDozen()
{ return numberedFunction(6); }

您在初始化列表中使用此指针。它是一个未初始化的对象。我想知道您是否可以成功编译此代码!

查看示例以查看绑定的用法(取自 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); 
}