我正在尝试为函数调用 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;
};
请注意,我要绑定(bind)到 this
,而不是 *this
。这避免了复制,但可能不是您想要的。
关于c++ - 成员函数替代名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6590581/