如何解决C++ 使用指向模板的成员指针传递参数类型
我正在尝试将 SomeStruct
的成员转换为非常量 void(*)()
的成员。为此,我使用了一个名为 Base
的类,它有一个模板成员函数 nc()
,它通过转换自身将成员指针转换为非常量指针:(static_cast<Derived *>(this)->*ptr)()
。
问题:我还需要它来处理 void
的接收参数(参见 main()
的第二行)。我是参数打包/解包和转发的新手,所以任何帮助将不胜感激!
到目前为止,这是我的代码(更新为更小的示例):
#include <utility>
#include <iostream>
template <typename Derived>
struct Base
{
template <void (Derived::*ptr)() const> // should also take arbitrary amount
void nc() // of params
{
(static_cast<Derived *>(this)->*ptr)();
}
};
struct SomeStruct: public Base<SomeStruct>
{
void exit() const;
void takesParam(int num);
};
inline void SomeStruct::exit() const
{
}
inline void SomeStruct::takesParam(int num)
{
}
int main()
{
auto ptr1 = &Base<SomeStruct>::nc<&SomeStruct::exit>; // works
//auto ptr2 = &Base<SomeStruct>::nc<&SomeStruct::takesParam>; // error
}
以及使用 g++-10
编译时得到的错误消息(未使用的变量可以忽略 ofc):
main.cc: In function ‘int main()’:
main.cc:31:36: error: unable to deduce ‘auto’ from ‘& nc<&SomeStruct::takesParam>’
31 | auto ptr2 = &Base<SomeStruct>::nc<&SomeStruct::takesParam>;
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cc:31:36: note: Couldn’t deduce template parameter ‘auto’
main.cc:30:10: warning: unused variable ‘ptr1’ [-Wunused-variable]
30 | auto ptr1 = &Base<SomeStruct>::nc<&SomeStruct::exit>; // works
| ^~~~
解决方法
我不确定您要实现的目标,但因为在 nc
的定义中,您有:
template <void (Derived::*ptr)() const>
void nc();
你不能引用 nc
与不同类型的成员函数,它应该像 void (Derived::*ptr)() const
。
但是您只需添加另一个重载,例如:
template <void (Derived::*ptr)(int)>
void nc();
然后解决您的问题,然后您可以同时拥有:
void (CPU::*CPU::s_opcode[])() =
{
&Base<CPU>::nc<&CPU::exit>,// accepting const works
&Base<CPU>::nc<&CPU::takesParam> // does not work
};
你可以像这样定义这个重载:
template <typename Derived>
template <void (Derived::*ptr)(int) >
void Base<Derived>::nc()
{
(static_cast<Derived *>(this)->*ptr)(0);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。