但是好像只能在int或者float上操作,不能操作
在std::vector,你能帮忙吗?
对于像搁浅容器这样的模板类,您需要指定模板参数来获取具体类型,然后您可以使用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);
}