a can not be explicitly specialized issue

My code as follows,and the compiler shows "C2910: 'Gobj<std::string>::operator []' : cannot be explicitly specialized\genericarray.cpp 32",it seems a hopeless implementation ,but I know I always look on the dark side too much,any kinds of help would be appreciated.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<cstdlib>
#include<iostream>
#include<string>
using namespace std;

template <class typea> class Gobj
{
public:
	typea a1[10];
	Gobj(){
		for(int tt=0;tt<10;tt++)
			a1[tt]=0;
	}

	typea &operator[](int i);
};

template <class typea> typea &Gobj<typea>::operator [](int i){
	return a1[i];
}
template <> class Gobj<string>{
public:
	string str[10];
	Gobj(){
		for(int tt=0;tt<10;tt++)
			str[tt]="explicitly specialized";
	}
	string &operator[](int i);
};
template<> string &Gobj<string>::operator [](int i){
	return str[i];
};


void main()
{
	Gobj<int> t;
	Gobj<string> sarray;
	int s;
	cout<<t[0];
	cout<<sarray[0];
	cin>>s;
}


remove the template<> and have:
1
2
3
string &Gobj<string>::operator [](int i){
	return str[i];
};//get rid of this extra ; as well 


As for the reason why:

***From C++ Templates the comple guide ***
3.3 Specializations of Class Templates
You can specialize a class template for certain template arguments.
Similar to the overloading of function templates (see page 15),
specializing class templates allows you to optimize implementations for certain types
or to fix a misbehavior of certain types for an instantiation of the class template.

However, if you specialize a class template, you must also specialize all member functions.
Although it is possible to specialize a single member function,
once you have done so, you can no longer specialize the whole class.

To specialize a class template, you have to declare the class
with a leading template<> and a specification of the types for
which the class template is specialized. The types are used as a template
argument and must be specified directly following the name of the class:

1
2
3
4
template<> 
class Stack<std::string> { 
  … 
}; 

For these specializations, any definition of a
member function must be defined as an "ordinary" member function,
with each occurrence of T being replaced by the specialized type:


1
2
3
4
void Stack<std::string>::push (std::string const& elem) 
{ 
    elems.push_back(elem);    // append copy of passed elem 
} 

Last edited on
I'm very appreciated . you gave me such sufficiency explaination more than I want.It‘s very helpful for me.
Topic archived. No new replies allowed.