Reputation: 1360
I've made a specialized template base on original template class like this:
Base template:
template <typename T>
class MyData {
public:
MyData(T param) : data(param) {}
T GetData() const {
return data;
}
private:
T data;
};
Specialized template:
template <>
class MyData<char*> {
public:
MyData(const char* param) {
int len = static_cast<int>(strlen(param));
data = new char[len + 1];
strcpy_s(data, static_cast<rsize_t>(len + 1), param);
}
~MyData() {
delete[] data;
}
const char* GetData() const {
return data;
}
private:
char* data;
};
This code works well, but I'm wondering if there any explicit conditions for the type of template specialization. For example, if I make function specialization, return type and all parameters' type must be the same.
template <>
const char* Add(const char* pLeft, const char* pRight) {
----------- ----------- -----------
| | |
+----------------+------------------+
...
}
In class MyData
, template type of class is char*
but the parameter type of constructor is const char*
. However, there is no error while compiling the code. So I want to know is there any type conditions like this in class template specialization.
Upvotes: 1
Views: 58
Reputation: 2324
There is a difference here between function specializations and class specializations. Class specializations may be completely different types with another set of members, functions and base classes. The following compiles well:
template <typename T>
class Foo
{
public:
void Bar() {}
private:
int val;
};
class Parent {};
template <>
class Foo<char> : public Parent
{
public:
void BarBar() {}
private:
double val;
};
int main()
{
Foo<int> f;
Foo<char> ff;
}
Upvotes: 1