成员函数备用名称
member function alternative names
我正在尝试为函数调用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);
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 备用函数语法/函数原型
- 当模板化函数实例化失败时,回退到备用函数
- 成员函数备用名称