【问题标题】:Can this member function selection code be written without std::invoke?这个成员函数选择代码可以不用std::invoke写吗?
【发布时间】:2020-12-10 18:33:56
【问题描述】:

我试图根据一些 constexpr 值选择成员 fn。然后我尝试调用选定的函数,但我收到了关于如何使用不正确的语法调用成员 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();

我试图将其称为“正确”但失败了。最后我使用了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;
}

godbolt link

注意:我对 C++20 解决方案很好,例如,如果一些 concepts 魔法可以帮助...

【问题讨论】:

  • std::invoke 的全部意义在于简化函数指针的使用,因此请使用它来代替奇怪的 (imo) -&gt;* 语法。如果需要,它也是来自 c++20 的 constexpr
  • @JakubDąbek 但我想有很多人发现它比 A 中的代码更难阅读

标签: c++ templates c++20 member-function-pointers std-invoke


【解决方案1】:

您可以将其称为normal member function pointer call。 正确的语法是

 return ((*this).*SelectedGetter<&S::fn1, &S::fn2>::fn)();

return (this->*SelectedGetter<&S::fn1, &S::fn2>::fn)();

(See a demo)


旁注:

  • 如果你在f中调用的函数是const,你也可以改成uint32_t f() const
  • 其次,您可以将SelectedGetter 替换为variable template(从 开始),现在您需要更少的输入

看起来像

// 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>)();
}

(See a demo)

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多