c – 在模板中转换成员函数指针

c – 在模板中转换成员函数指针,第1张

概述假设我有以下两个类: template<typename T>struct Base{ void foo();};struct Derived : Base<Derived> {}; 我可以做这个: void (Derived::*thing)() = &Derived::foo; 编译器很高兴(正如我所料). 当我把它放在两个级别的模板中时突然爆炸: template<type 假设我有以下两个类:
template<typename T>struct Base{    voID foo();};struct Derived : Base<Derived> {};

我可以做这个:

voID (Derived::*thing)() = &Derived::foo;

编译器很高兴(正如我所料).

当我把它放在两个级别的模板中时突然爆炸:

template<typename T,T thing>struct bar {};template<typename T>voID foo(){    bar<voID (T::*)(),&T::foo>{};}int main(){    foo<Derived>();  // ERROR    foo<Base<Derived>>(); // Works fine}

这失败了:

non-type template argument of type 'voID (Base<Derived>::*)()' cannot be converted to a value of type 'voID (Derived::*)()'

godbolt

为什么简单的案例工作而更复杂的案例失败了?我相信这与this问题有关,但我并不完全确定….

解决方法 @YSC钉出了& Derived :: foo;的类型.既然你想知道为什么这个隐式转换……
voID (Derived::*thing)() = &Derived::foo;

…飞行正常但不在模板中,原因如下:

[temp.arg.nontype]

07001 A template-argument for a non-type template-parameter shall be a
converted constant Expression of the type of the template-parameter.

[expr.const]

07002 A converted constant Expression of type T is an Expression,
implicitly converted to type T,where the converted Expression is a
constant Expression and the implicit conversion sequence contains only

[…]

我省略的列表不包含pointer to member conversions.因此,使该模板参数对您指定的参数无效.

一个简单的解决方法是使用decltype(& T :: foo)而不是voID(T :: *)()作为类型参数.这是一个结构良好的替代品:

bar<decltype(&T::foo),&T::foo>{};

无论是否可接受,当然取决于您的用例,超出了MCVE的范围.

总结

以上是内存溢出为你收集整理的c – 在模板中转换成员函数指针全部内容,希望文章能够帮你解决c – 在模板中转换成员函数指针所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1255898.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存