c++ - std::forward 转发函数

标签 c++ templates forward-reference

我有以下代码无法编译,尤其是在通过 std::forward 转发之后

struct TestParent
{
    template< typename Fn >
    bool test( Fn&& fn )
    {
        //.. do something
        //.. check some condition
        bool someCondition = true;
        if ( someCondition )

        {
            //this call works!
            return fn();
        }

        return testAtNextLevel( std::forward< Fn >( fn ) );
    }

    template < typename Fn >
    bool testAtNextLevel( Fn&& fn )
    {
        if ( (this->*fn() )
        {
             return true;
        }

         //... test some more
         return true;
     }
}

struct TestChild: public TestParent
{
     bool thisTestOk();
     bool testAll();
}

bool TestChild::thisTestOk()
{
     return true;
}

bool testAll()
{
    auto myFunc = std::bind( &TestChild::thisTestOk, this );
    return test( myFunc );
}

编译时我得到了这个错误信息:

error: no match for 'operator->*' (operand types are 'TestParent*' and 'std::_Bind<std::_Mem_fn<bool (TestChild::*)()>(TestChild*)>')
 if ( (this->*fn)() )

有人知道为什么在通过 std::forward 之后,函数就不能被调用了吗?在基类中,就在调用“testAtNextLevel”之前,如果满足某些条件,我们可以只调用传入的函数,而不是在它被转发到另一个模板函数之后?

最佳答案

使用所有这些模板和 auto 声明,很容易忘记您正在处理的数据类型。让我们从靠近代码底部的地方开始:

auto myFunc = std::bind( &TestChild::thisTestOk, this );

什么是myFunc?虽然 std::bind 的返回类型未被正式指定,但它的使用是指定的(例如,参见 cppreference.com)。将此返回值作为函数调用等同于调用 thisTestOk(),并将其单独的参数绑定(bind)到 this

也就是说,指向TestChild 参数的隐藏指针(存在于所有TestChild 的非静态成员函数中)已被替换为this ,它具有将成员函数转换为非成员函数的作用。现在让我们看看如何调用这个包装器非成员函数。

test() 中,这个包装器通过 return fn() 调用。它作为一个函数被调用,并按预期工作。

testAtNextLevel() 中,此包装器通过 this->*fn() 调用。此包装器非成员 函数作为指向成员函数的指针被调用,这是一个错误。为了使其在句法上有效,调用应该只是 fn(),就像在 test() 中一样。如果你真的想覆盖绑定(bind)对象并使用 this 作为 fn() 的隐藏参数,你需要传递一些不同的东西作为参数给 testAtNextLevel( ),可能是指向成员的指针(它必须是指向-TestParent-成员的指针,而不是指向-TestChild 的指针-成员)。

关于c++ - std::forward 转发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53197249/

相关文章:

c++ - 从 DLL 创建和导出 C++ 单例类

c++ - 去除 boost::fusion 序列中的引用

c++ - 函数调用父类方法而不是子类?

c++ - 如何在编译时检查函数是否具有默认参数值?

c++ - _Decimal64 在 C++ 中没有类型

java - 为什么我必须使用 "this"关键字进行前向引用?

python - Google App Engine 模板循环遍历两个变量

c++ - 计算斐波那契数的模板元编程

java - Java 中静态和非静态前向引用的内部工作