c++ - 将不同的变量传递给模板函数
问题描述
我有一个为 2 个变量分配一些值的函数:
bool get(int& value1, string& value2);
我需要使用这些返回的变量之一调用模板函数。我该怎么做?
bool get(int& value1, string& value2) { /* assign them */ };
template<typename T>
doWork(const T& value) { /* do some work */ };
template<typename T>
void foo() {
int value1;
string value2;
get(value1, value2);
while(doWork(/*if T == int, pass value1, otherwise value2*/)) {
// do smth
}
};
解决方案
您可以将if constexpr
(C++17 起) 与std::is_same
(from <type_traits>
) 一起使用。当您想在循环条件中使用它时,我将它包装在一个 lambda 中:
template<typename T>
void foo() {
int value1;
string value2;
get(value1, value2);
auto doWorkIntOrString = [&](){
if constexpr (std::is_same_v<int,T>) return doWork(value1);
else return doWork(value2);
};
while(doWorkIntOrString()) {
// do smth
}
};
推荐阅读
- raspberry-pi - VMWare ESXi VM 创建错误“无法创建虚拟机 vm1。找不到 vm1.vmdk”
- php - 在 Bluehost VPS 上迁移 WordPress 网站的问题(未指定输入文件)
- javascript - ML5 神经网络的基本训练不起作用
- here-api - 如何使用 API 密钥执行 Here Fuel API?
- ios - 如何以编程方式将 UIStackview 放在 Swift 中的 UIView 中
- python - apscheduler:返回了多个 DjangoJobExecution -- 它返回了 2
- c# - SQL 多个查询同时产生死锁(UPDLOCK)
- list - 您将如何在包含元组列表的元组列表上使用 map?
- python-3.x - Telethon 按钮事件每次都在另一个循环中运行
- python - 从满足数据框 Python 条件的列表中索引并保存最后 N 个点