c++ - C++:递归匹配参数类型与类模板类型
问题描述
我希望实现这样的类型匹配功能:
MyClass<int, bool> temp;
temp.print(-1, false); // works
temp.print(-1); // compile error, too less argument
temp.print(-1, "string"); // compile error, wrong type
temp.print(-1, false, 'c'); // compile error, too many arguments
基本上,当给定模板参数时,MyClass
的函数print
接受完全相同类型的参数,不多也不少。
这是我目前的实现:
template<class... ClassType>
class MyClass {
public:
template<typename... ArgType>
void print(ArgType... args) {
matchType<ClassType...>(args...);
}
private:
template<typename Type>
void matchType(Type t) {
std::cout << "matching " << t << "\n";
std::cout << "end\n";
}
template<typename FirstType, typename... Rest>
void matchType(FirstType firstArg, Rest... args) {
std::cout << "matching " << firstArg << "\n";
matchType<Rest...>(args...);
}
};
但它无法检测和匹配它为代码编译得很好的类型:
MyClass<int, bool> temp;
temp.print(-1, false); // works
temp.print(-1, "string"); // works, shouldn't work
temp.print(-1, false, 'c'); // works, shouldn't work
有人可以向我解释我做错了什么吗?
解决方案
#include <iostream>
template<class... ClassType>
class MyClass {
public:
template<typename... ArgType>
void print(ArgType... args) = delete;
void print(ClassType ... args) {
std::cout << "works\n";
}
};
int main()
{
MyClass<int, bool> temp;
temp.print(-1, false); // ok
temp.print(-1); // error
temp.print(-1, "string"); // error
temp.print(-1, false, 'c'); // error
temp.print(-1L, false); // error
}
推荐阅读
- apache - 如何以非 root 用户身份运行 Apache?
- java - Alpha Numeric Random Number Sequence [5-digit or 6-digit or any digit] generation
- azure-devops - 如何使用部署组的 Azure 管道代理了解在 DevOps 发布期间跳过了哪些机器
- python - 如何在python中以指定的方式顺序添加重复行?
- c# - 如何将列表的每个元素修改为新列表?
- apache - 不以正斜杠 / 开头的 Apache 访问日志请求
- spotify-app - 如何使用 Spotify API 查找两位艺术家之间的路径
- angular - 升级到 Angular 10 后出现 Webpack 错误
- python - 转换为字符串后如何在打印命令中使用 \n 转义字符?
- r - 如何在数据框列表中将 data.frame 中的列命名为数据框的名称