gpt4 book ai didi

带有模板化参数的 C++ 函数模板

转载 作者:搜寻专家 更新时间:2023-10-31 00:45:15 25 4
gpt4 key购买 nike

我正在尝试编写一个可以将任何标准容器(列表、堆栈、 vector 等)作为参数的函数。我还想知道容器中的类型。这是我尝试过的。

#include<iostream>
#include<list>
#include<vector>

template<class data_type, template<class> class container_type>
void type(container_type<data_type>& _container){
std::cout<<typeid(container_type).name()<<std::endl;
}


int main(){

std::list<int> list_t;
std::vector<int> vector_t;
type(list_t);
type(vector_t);
}

一旦在此函数中,container_type 的类型始终是 _Container_base_aux_alloc_empty,(我认为)它是标准容器的基类。

这是怎么回事?

如何让这个函数返回正确的类型?

最佳答案

container_type的typeid是没有用的,因为那只是一个模板类,而模板类根本就不是真正的类型,它只是在实例化之后才成为一个。所以你真正想要的是 data_type 的类型对于值类型,以及 container_type<data_type> 的类型对于实例化容器的类型。当然,更好的是采取container_type<data_type>::value_type作为值类型。

请注意,大多数容器采用多个模板参数,因此您最好使用可变模板来编写:

template <template <typename...> class Container, typename ...Args>
void print_type(const Container<Args...> &)
{
typedef typename Container<Args...>::value_type value_type;
print(typeid(Container<Args...>).name());
print(typeid(value_type).name());
}

关于带有模板化参数的 C++ 函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7140294/

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