But it seems it just can operate on int
or float
, cant be operated
on std::vector
, can you help on this?
For template classes like stranded containers, you need to specify the template argument to get the concrete type and thereafter you can compare usingstd::is_same
. That means something like std::is_same_v<T, std::vector<int>>
or std::is_same_v<T, std::vector<float>>
, etc... will work.
On the other side, you need to see whether the passed container is a specialization for the standard container. There you need your own std::is_same_v
like type traits.
One possible implementation will look like as follows. Also note that you need to use the if constexpr
(since c++17) instead of normal if
for compile time branching. If no access to c++17, you need to use 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);
}