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;
}
Note: Out of curiosity, I tried adding multiple template<>. Ie,
template<>
template<>
template<>
template<typename T>
struct PrintMe<std::vector<T>>
This still compiles with Intel, but not with g++. Not sure what that means, but it's interesting.
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.
Given the definition of the class template,
template<> // <--- optional?
template<typename T>
struct PrintMe<std::vector<T>> { ... };
is not valid.
You need to remove that line and use:
template<typename T>
struct PrintMe<std::vector<T>> { ... };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With