如何解决可以在没有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
的魔术可以帮助您...
解决方法
您可以像normal member function pointer call这样称呼它。 正确的语法是
return ((*this).*SelectedGetter<&S::fn1,&S::fn2>::fn)();
或
return (this->*SelectedGetter<&S::fn1,&S::fn2>::fn)();
旁注:
- 如果您在
f
中调用的函数是const
,那么您也可以将其设为uint32_t f() const
- 第二,您可以将
SelectedGetter
替换为variable template(自c++14起),现在您不需要键入内容了
看起来像
// 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>)();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。