gpt4 book ai didi

C++ - 将模板类型对象转换为特定数据类型

转载 作者:行者123 更新时间:2023-11-30 03:42:46 24 4
gpt4 key购买 nike

我正在使用模板函数 searchByCriteria<T>我希望能够同时使用 string 运行函数和一个 double .我有一个包含 string 的自定义对象列表和 double属性,我希望能够使用此函数来检查条件值(用户输入的任何类型),以检查相同类型的对象属性中的匹配项。

即用户输入 double 值,检查对象集合以匹配 double 值。用户输入一个字符串值,检查对象集合中匹配的字符串值。

我遇到的问题是,一旦输入值,它就会被传递给另一个模板函数,以根据列表中的元素进行检查。在这一点上,T作为参数传递的对象需要转换为 double 或字符串以允许检查匹配项。

这是这部分的代码:

//get a sub-list of transactions
//of all that match specified search criteria
template <typename T>
const TransactionList TransactionList::getTransactionsForSearchCriteria(T criteria) const {
//make a copy of list to avoid deleting existing data
TransactionList copy(*this);
//to have appropriate transactions added in
//then returned as copy
TransactionList ret;

//////////////////////////////////////////
//before checking for matches can start///
//must ID datatype of T instance//////////
//////////////////////////////////////////

//check all transactions until list empty
while (copy.size() > 0)
{
//check that criteria matches transaction attribute
if (/*converted criteria matches corresponding attribute*/)
{
//flag as match
}
}
}

可以看到,参数值criteria在进入 while 循环以检查匹配之前,需要将其转换回特定的数据类型。我不知道如何执行此操作,因为我不知道 C++ 中的任何转换方法在这种情况下会有用。

我唯一能想到的是:

try
{
//example method
convertToDouble(criteria);
}
catch (SomeKindOfNumberException ex)
{
//cannot be a double
//so must be string
convertToString(criteria);
}

非常感谢任何帮助。

谢谢,标记

最佳答案

这样的事情怎么样?

#include <iostream>

template<typename T>
T FuncB(T x) {
std::cout << "generic T ";
return x;
}

template<>
double FuncB<double>(double x) {
std::cout << "double ";
return 0.123;
}

template<>
std::string FuncB<std::string>(std::string x) {
std::cout << "string ";
return "xyz";
}

template <typename T>
void FuncA(T param) {
std::cout << "FuncA: ";
T tmp = FuncB(param);
std::cout << tmp << std::endl;
}

int main() {
std::string s = "abc";

FuncA(0.1);
FuncA(s);
FuncA(1);
}

FuncA 可以接收任何 T,但它使用专用于某些特定类型的 FuncB。如果您愿意,可以保留或删除 FuncB(T) 以支持/避免使用未知类型。

前面代码的输出如下:

FuncA: double 0.123
FuncA: string xyz
FuncA: generic T 1

关于C++ - 将模板类型对象转换为特定数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36645057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com