使用此类型函数有什么优势

What is the advantage of using this Type Function?

本文关键字:什么 函数 类型      更新时间:2023-10-16

>在"C++ Templats Complete Guide 2nd Edition"一书"19.3 Type Functions"一节中,它提出了以下问题:

假设我们有许多容器模板,例如 std::vector<> 和 std::list<>,以及内置数组。我们想要一个 类型函数,给定这样的容器类型,生成元素 类型。这可以通过部分专业化来实现。

然后提供以下答案:

#include <vector>
#include <list>
#include <iostream>
#include <typeinfo>
template<typename T>
struct ElementT;
template<typename T>
struct ElementT<std::vector<T>>
{
    using Type = T;
};
template<typename T>
struct ElementT<std::list<T>>
{
    using Type = T;
};
template<typename T, std::size_t N>
struct ElementT<T[N]>
{
    using Type = T;
};
template<typename T>
struct ElementT<T[]>
{
    using Type = T;
};
template<typename T>
void printElementType(T const& c)
{
    std::cout << "Container of "
              << typeid(typename ElementT<T>::Type).name()
              << " elementsn";
}
int main()
{
    std::vector<int> intVec = {1, 2, 3};
    std::list<double> doubleList = {1.1, 2.2, 3.3};
    bool boolArr[] = {false, false, true, false, true};
                                  //GNU COMPILER:
    printElementType(intVec);     //Container of i elements
    printElementType(doubleList); //Container of d elements
    printElementType(boolArr);    //Container of b elements
}

我的问题是,当我们可以编写像波纹管这样的简单函数时,这种方法的优势是什么?

#include <iostream>
#include <typeinfo>
#include <vector>
#include <list>
template<typename T>
void printType(const T& container)
{
    std::cout << "Container of " 
              << typeid(T).name() 
              << " elementsn";
}
int main()
{
    std::vector<int> intVec = {1, 2, 3};
    std::list<double> doubleList = {1.1, 2.2, 3.3};
    bool boolArr[] = {false, false, true, false, true};
                           //GNU COMPILER: 
    printType(intVec);     //Container of St6vectorIiSaIiEE elements
    printType(doubleList); //Container of St4listIdSaIdEE elements
    printType(boolArr);    //Container of A5_b elements
}

还有第二个问题:为什么结果不同?这些额外信息是什么?

谢谢。

2 个主要区别:

  1. 书籍版本获取容器中元素的类型,而您的版本仅打印容器的类型。此外,您的版本接受任何类型,即使它不是容器。例如,在书的版本中,类型是int,而在您的版本中是std::vector<int>

  2. 书籍版本"获取"类型。这可以进一步用于定义其他类型。您的版本将打印信息。除了打印它,您不能做任何其他事情。不能使用它来组合其他类型或声明变量。

    这就像两者之间的区别:

    int max(int a, int b)
    {
        if (a > b)
            return a ;
        else
            return b;
    }
    

    void print_max(int a, int b)
    {
        if (a > b)
            std::cout << a << 'n';
        else
            std::cout << b << 'n';
    }
    

    第一个功能远远优于第二个功能。您可以使用它来执行仅打印最大值的其他操作。例如:

    int max(int a, int b, int c) { return max(a, max(b, c)); }
    

    您可以对图书版本执行哪些操作的示例,但不能使用您的版本:

    template <class Container>
    typename ElementT<Container>::Type foo(const Container& cont) 
    {
         typename ElementT<Container>::Type sum = 0;
         for (const auto& e : cont)
         {
              sum += e;
         }
         return sum;
    }