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();
我试图称之为“正确”但失败了。最后我使用的是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;
}
注意:我对 C++20 解决方案没问题,例如,如果某些concept魔法可以帮助...
你可以像普通的成员函数指针调用一样调用它。正确的语法是
 return ((*this).*SelectedGetter<&S::fn1, &S::fn2>::fn)();
或者
return (this->*SelectedGetter<&S::fn1, &S::fn2>::fn)();
(见演示)
旁注:
它看起来像
// 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>)();
}
(见演示)
| 归档时间: | 
 | 
| 查看次数: | 94 次 | 
| 最近记录: |