I want to specialize a templated class with a templated type. Something like this..
#include <iostream>
#include <vector>
#include <string>
using namespace std; // I know, I know. For brevity here.
template < typename T > class MyClass
{
public:
string print_sum();
vector < T > m_Data;
};
template < typename T >
string MyClass< T >::print_sum()
{
T sum = 0;
for ( auto it = m_Data.begin(); it != m_Data.end(); ++it )
{
sum += *it;
}
return to_string( sum );
}
/*
// Does not work
template < typename S >
string MyClass< vector < S > >::print_sum()
{
S sum = 0;
for ( auto it = m_Data.begin(); it != m_Data.end(); ++it )
{
for ( auto it2 = (*it).begin(); it2 != (*it).end(); ++it2 )
{
sum += *it2;
}
}
return to_string( sum );
}
*/
template <>
string MyClass< vector < int > >::print_sum()
{
int sum = 0;
for ( auto it = m_Data.begin(); it != m_Data.end(); ++it )
{
for ( auto it2 = (*it).begin(); it2 != (*it).end(); ++it2 )
{
sum += *it2;
}
}
return to_string( sum );
}
int main()
{
vector<int> d = {1, 2, 3, 4, 5};
MyClass<int> foo;
foo.m_Data = d;
std::cout << foo.print_sum() << std::endl;
vector < vector < int > > m = {d, d, d};
MyClass < vector < int > > bar;
bar.m_Data = m;
std::cout << bar.print_sum() << std::endl;
return 0;
}
I’d like something like the commented out version so I can have code that will work for various vector < vector < S > >
.
Upon removing the comments gcc says:
main.cpp:26:43: error: invalid use of incomplete type ‘class MyClass >’
26 | string MyClass< vector < S > >::print_sum()
| ^
main.cpp:7:31: note: declaration of ‘class MyClass >’
7 | template < typename T > class MyClass
| ^~~~~~~
main.cpp: In instantiation of ‘std::string MyClass<T>::print_sum() [with T = std::vector<int>; std::string = std::__cxx11::basic_string<char>]’:
main.cpp:51:31: required from here
I can’t sort out how to make this work.
Bonus points if we can do some sort of typedef
magic to make something like this work:
typedef
template < typename S >
class MyClass < vector < S > > MyVecClass < S >;
// To allow
MyVecClass < int > bar;
// instead of
MyClass < vector < int > > bar;
1