我想为STL容器设计一个打印函数,包括:std::vector, std::map, std::unodered_map, std::set, std::unordered_set, std::list
....
理想的函数如下所示:
template<typename T>
void Show(const T& t)
{
if (istype(t, std::vector))
{
// here is a presudo code
// print vector
for (auto i: t) cout << i << endl;
}
else if (istype(t, std::unordered_map))
{
// print unordered_map
}
else
{ }
}
我认为问题发生在istype()
我知道像 std::is_same
这样的函数可以做到这一点。
但是好像只能操作int
或者float
,不能操作std::vector
,你能帮忙吗?
最佳答案
But it seems it just can operate on
int
orfloat
, cant be operated onstd::vector
, can you help on this?
对于像搁浅容器这样的模板类,您需要指定模板参数以获取具体类型,然后您可以使用std::is_same
进行比较。 .这意味着类似于 std::is_same_v<T, std::vector<int>>
或 std::is_same_v<T, std::vector<float>>
等...将起作用。
另一方面,您需要查看传递的容器是否是标准容器的特化。你需要自己的 std::is_same_v
喜欢类型特征。
一种可能的实现如下所示。另请注意,您需要使用 if constexpr
(自 c++17 开始)而不是正常的 if
用于编译时分支。如果无法访问 c++17 , 你需要使用 SFINAE .
( See a Demo )
#include <iostream>
#include <type_traits> // std::false_type, std::true_type
#include <vector>
#include <list>
#include <string>
#include <map>
template<typename Type, template<typename...> class Args>
struct is_specialization final : std::false_type {};
template<template<typename...> class Type, typename... Args>
struct is_specialization<Type<Args...>, Type> : std::true_type {};
template<typename ContainerType>
constexpr void show(const ContainerType& container) noexcept
{
if constexpr (is_specialization<ContainerType, std::vector>::value
|| is_specialization<ContainerType, std::list>::value)
{
for (const auto ele : container)
std::cout << ele << '\t';
std::cout << '\n';
}
else if constexpr (is_specialization<ContainerType, std::map>::value)
{
for (const auto& [key, value]: container)
std::cout << key << " " << value << '\t';
std::cout << '\n';
}
// ... so on!
}
int main()
{
std::vector<int> vec{ 1, 2, 3 };
show(vec);
std::list<int> list{ 11, 22, 33 };
show(list);
std::map<int, std::string> mp{ {1, "string1"}, {2, "string2"}, {3, "string3"} };
show(mp);
}
关于c++ - 模板函数中如何实现模板类类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68435070/