c++ - 错误:参数打包类模板中类模板的参数过多
问题描述
我创建了一个主模板和两个特化:一个用于 void 类型,另一个是用于不同参数类型的参数包。
后台是一个“连接”引擎,用来连接返回void的成员函数,所以我不需要返回类型,只需要参数类型。这些类就像包装器一样,提供了一个语法友好的静态函数来创建具体的链接。
所以我的代码如下所示:
/**
* CalleeCreator class, primary template
*/
template <typename T> class CalleeCreator;
template <typename... TParams>
class CalleeCreator<TParams...> final
{
public:
template <typename TObject, void(TObject::*Function)(TParams...)>
constexpr static void create(const char*name, TObject& instance)
{
new Callee< void (TObject::*)(TParams...), Function>( name, instance);
}
};
template <>
class CalleeCreator<void> final
{
template <typename TObject, void(TObject::*Function)(void)>
constexpr static void create(const char* name, TObject& instance)
{
new Callee< void (TObject::*)(void), Function>( name, instance);
}
};
一旦我打电话给这样的事情:
CalleeCreator<uint8_t, uint16_t>::create<Object,
&Object::method> ("test", *this);
我得到那个编译错误:错误:类模板的参数太多。
打电话时
CalleeCreator<void>::create<Object,
&Object::method> ("test", *this);
按预期工作
我不明白的是,我创建了另一个具有返回类型和相同主模板的版本:
template <typename TReturn, typename... TParams>
class CalleeCreator<TReturn(TParams...)> final
{
public:
template <typename TObject, TReturn(TObject::*Function)(TParams...)>
constexpr static void create(ConstCharPtr name, TObject& instance)
{
new Callee< TReturn (TObject::*)(TParams...), Function>( name, instance);
}
};
template <typename TReturn>
class CalleeCreator<TReturn(void)> final
{
public:
template <typename TObject, TReturn(TObject::*Function)(void)>
constexpr static void create(ConstCharPtr name, TObject& instance)
{
new Callee< TReturn (TObject::*)(void), Function>( name, instance);
}
};
如果我打电话给他们,一切都很好并且工作:
CalleeCreator<void(uint8_t, uint16_t)>::create<Object,
&Object::method> ("test", *this);
我不明白我在这里做错了什么。
此外,Callee 类可以查看模板和构造函数。
/** Class Callee, primary
*/
template <typename T, T> class Callee;
template <typename TObject, typename... TParams,
void (TObject::*Function)(TParams...)>
class Callee<void (TObject::*)(TParams...), Function> final
{
public:
Callee(const char* name, TObject& instance){}
};
当然,还有一个 Callee 类,其返回类型也适用于其他解决方案。
解决方案
您只需要一个主要的可变参数类模板:
template <typename... TParams>
class CalleeCreator final
{
// ...
};
您不需要部分专业化,也不需要专门R(void)
化 - 这是一个古老的(来自 C),在 C++ 中编写一个采用 0 参数的函数类型的方法是使用空括号。
推荐阅读
- excel - 高级查找公式
- python - 函数参数中的动态变量
- javascript - 传单绘制“无法读取未定义的属性'启用'”向geoJSON图层添加控件
- python - 带有哈里斯角检测的2张图像的Python OpenCV搜索对应关系
- php - 卡住了 - 通过 Curl 上传数据二进制选项
- java - 开源远程呼叫指标跟踪
- python - Pandas 用 Nan 将两列相加
- java - 从 FirebaseAdapter 的 Listview 中删除或隐藏列表项
- html - 使用 Container 和 Columns 使用 Bootstrap 设置正确的边距/填充
- c# - 如何将字符串值从父表单发送到子表单(反之亦然)