这个成员函数选择代码可以在没有 std::invoke 的情况下编写吗?

NoS*_*tAl 5 c++ templates member-function-pointers c++20 std-invoke

我试图fn根据某个constexpr值选择一个成员。然后我尝试调用选定的函数,但是我收到了关于如何fn使用不正确的语法调用成员的错误。

error: must use '.*' or '->*' to call pointer-to-member function in
'S::SelectedGetter<&S::fn1, &S::fn2>::fn (...)', e.g. '(... ->*
S::SelectedGetter<&S::fn1, &S::fn2>::fn) (...)'     
    18 |     return SelectedGetter<&S::fn1, &S::fn2>::fn();
Run Code Online (Sandbox Code Playgroud)

我试图称之为“正确”但失败了。最后我使用的是std::invoke,但我想知道这是否可以在没有 的情况下完成std::invoke,只使用“原始”C++ 语法。

#include <algorithm>
#include <type_traits>

static constexpr int number = 18;

struct S
{
    using GetterFn = uint32_t(S::*)() const;
    uint32_t fn1()const {
        return 47;
    }
    uint32_t fn2() const {
        return 8472;
    }

    template <GetterFn Getter1, GetterFn Getter2>
    struct SelectedGetter
    {
        static constexpr GetterFn fn = (number < 11) ? Getter1 : Getter2;
    };

    uint32_t f() {
        return std::invoke((SelectedGetter<&S::fn1, &S::fn2>::fn), this);
    }
};

int main() 
{
    return S{}.f() % 100;
}
Run Code Online (Sandbox Code Playgroud)

神箭链接

注意:我对 C++20 解决方案没问题,例如,如果某些concept魔法可以帮助...

JeJ*_*eJo 8

你可以像普通的成员函数指针调用一样调用它。正确的语法是

 return ((*this).*SelectedGetter<&S::fn1, &S::fn2>::fn)();
Run Code Online (Sandbox Code Playgroud)

或者

return (this->*SelectedGetter<&S::fn1, &S::fn2>::fn)();
Run Code Online (Sandbox Code Playgroud)

见演示


旁注:

  • 如果你调用的函数fconst,你也可以让它也uint32_t f() const
  • 其次,你可以SelectedGetter用一个变量模板)替换,现在你需要更少的输入

它看起来像

// variable template
template<GetterFn Getter1, GetterFn Getter2>
static constexpr auto fn = (number < 11) ? Getter1 : Getter2;

uint32_t f() const {
   return (this->*fn<&S::fn1, &S::fn2>)();
}
Run Code Online (Sandbox Code Playgroud)

见演示