gpt4 book ai didi

c++ - 如何测试 map 中包含的类型

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

假设我有一个模板函数可以像这样计算 map 元素的总和:

template <class A, class B> double Total(const map<A, B>& cntr)
{
map<A, B>::const_iterator iter;
double total = 0;

for (iter = cntr.begin(); iter != cntr.end(); ++iter)
total += iter->second;

return total;
}

只要 B 是数字类型,它就可以正常工作;但是,很明显,如果您传递了对类似 map<int, string> 的引用,那是行不通的。

我想知道如何测试映射的非键部分中包含的类型,以便我可以通过异常或其他方式。我尝试使用 isdigit() 但似乎无法获得有效版本。

编辑:我对测试的预期用途是添加功能,以便始终使用 int 类型来计算总数,因此我可以传入 map<int, string>map<string, int>它将始终计算 int 类型。

最佳答案

您可以在 C++11 或 boost 中使用类型特征。

#include <type_traits>

template <class A, class B> double Sum(const map<A, B>& cntr)
{
static_assert(std::is_arithmetic<B>::value, "Invalid type!");
map<A, B>::const_iterator iter;
double total = 0;

for (iter = cntr.begin(); iter != cntr.end(); ++iter)
total += iter->second;

return total;
}

请记住,即使没有断言,无效类型也不会编译。

关于c++ - 如何测试 map 中包含的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9150564/

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