c++ - 模板函数中如何实现模板类类型?

标签 c++ templates c++17 c++-standard-library function-templates

我想为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 or float, cant be operated on std::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 (自 开始)而不是正常的 if用于编译时分支。如果无法访问 , 你需要使用 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/

相关文章:

c++ - 在OpenCV C++中播放视频文件

c++ - 添加二进制数(作为数组)C++

C++ 编译时子串

c++ - 使用折叠表达式初始化静态 constexpr 类数据成员不编译

c++ - 通用树类的继承

c++ - 返回子类实例的父类(super class)中的方法

Python - Jinja2 中使用 unicode 字符串格式化日期时间

Python Mako 模板 - 如何根据上下文中的值动态决定调用哪个 def 或函数?

c++ - 类模板的外部成员函数

c++ - 为什么输入流不识别 Ctrl D 而给出一个无限循环?