矢量类型的模板类特化 - 不同的有效语法? [英] Template class specialization for vector type - different valid syntax?
问题描述
在以下代码段中,template<>
对于专业化是可选的吗?我是否包含它有什么区别吗?我的第一直觉是将它包括在内,因为它或多或少表明它是一种专业化.它在 g++ 4.9.2 和 Intel 16 下以两种方式编译
In the following snippit, is the template<>
optional for the specialization? Is there any difference whether I include it or not? My first instinct was to include it as it more-or-less signifies that it is a specialization. It compiles both ways under both g++ 4.9.2 and 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<>
.即,
Note: Out of curiosity, I tried adding multiple template<>
. Ie,
template<>
template<>
template<>
template<typename T>
struct PrintMe<std::vector<T>>
这仍然可以用 Intel 编译,但不能用 g++ 编译.不确定这意味着什么,但很有趣.
This still compiles with Intel, but not with g++. Not sure what that means, but it's interesting.
注意 2:哇,这和我 5 年前的一个问题非常相似:模板类特化,其中模板参数是模板.在那里它被称为冗余语法.
Note 2: Wow, this is very similar to a question of mine from 5 years ago: Templated class specialization where template argument is a template . There it was mentioned as redundant syntax.
推荐答案
给定类模板的定义,
template<> // <--- optional?
template<typename T>
struct PrintMe<std::vector<T>> { ... };
无效.
您需要删除该行并使用:
You need to remove that line and use:
template<typename T>
struct PrintMe<std::vector<T>> { ... };
这篇关于矢量类型的模板类特化 - 不同的有效语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!