【发布时间】: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;
}
注意:我对 C++20 解决方案很好,例如,如果一些 concepts 魔法可以帮助...
【问题讨论】:
-
std::invoke的全部意义在于简化函数指针的使用,因此请使用它来代替奇怪的 (imo)->*语法。如果需要,它也是来自 c++20 的constexpr。 -
@JakubDąbek 但我想有很多人发现它比 A 中的代码更难阅读
标签: c++ templates c++20 member-function-pointers std-invoke