向量类型的模板 class 专业化 - 不同的有效语法?

Template class specialization for vector type - different valid syntax?

在下面的代码片段中,template<> 是可选的专业化吗?我是否包含它有什么区别吗?我的第一直觉是将它包括在内,因为它或多或少意味着它是一个专业化。它在 g++ 4.9.2 和 Intel 16

下以两种方式编译
#include <vector>
#include <iostream>

template<typename T>
struct PrintMe
{
    static void Print(const T & t)
    {
        std::cout << "In general templated struct: " << t << "\n";
    }   
};      


template<> // <--- optional?
template<typename T>
struct PrintMe<std::vector<T>>
{   
    static void Print(const std::vector<T> & t)
    {   
        std::cout << "In general specialization for vector: " << t.size() << "\n";
        for(const auto & it : t)
            std::cout << "        " << it << "\n";
    }

};


int main(void)
{   
    PrintMe<int>::Print(5);   
    PrintMe<double>::Print(5);    
    PrintMe<std::vector<float>>::Print({10,20,30,40});

    return 0;
}

注意:出于好奇,我尝试添加多个 template<>。即,

template<>
template<>
template<>
template<typename T>
struct PrintMe<std::vector<T>>

这仍然可以使用 Intel 进行编译,但不能使用 g++。不确定那是什么意思,但这很有趣。

注2:哇,这和我5年前的一个问题非常相似:Templated class specialization where template argument is a template。那里提到它是冗余语法。

根据 class 模板的定义,

template<> // <--- optional?
template<typename T>
struct PrintMe<std::vector<T>> { ... };

无效。

您需要删除该行并使用:

template<typename T>
struct PrintMe<std::vector<T>> { ... };

有很多方法可以查看模板和模板专业化,它们可以描绘出更好的画面并使整个事情更加清晰。 在这种情况下,对我来说更简单的方法是不要去想

template<typename T>
struct PrintMe<std::vector<T>> { ... };

作为

的专业化
template<typename T>
struct PrintMe { ... };

但作为完全不同的 class 模板,恰好两者具有相似的命名方法。