gpt4 book ai didi

c++ - 如何创建容器和类型都是参数的模板函数?

转载 作者:太空宇宙 更新时间:2023-11-04 14:45:17 25 4
gpt4 key购买 nike

这可能是一个微不足道的问题,但让我发疯。我想定义一个函数 foo()这将适用于不同的容器,例如: vector<int> , vector<double> , set<int>set<double> .

我试过这样定义 foo:

template<typename CONT, typename T>
int foo(CONT<T>){
//evaluate x
return (int) x ;
}

这种定义是行不通的,但我不明白为什么。

我怎样才能实现类似的目标?

最佳答案

同时指定容器类模板及其实例化的方法是使用template模板参数:

template <template <typename...> class Cont, typename T>
int foo(Cont<T>) {
...
}

请注意,Cont 使用了可变数量的参数,否则它不会覆盖标准容器具有的未知数量的默认模板参数。

关于c++ - 如何创建容器和类型都是参数的模板函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12965082/

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