I'm just starting with C++, and I'm trying to create a class that extends the functionalities of basic_string < unsigned char > to let it accept chars as arguments for the constructors too, and they'd be handled by casting them and calling the base constructors for basic_string.
I've been told to use template specialization for that, but I've been struggling with it, so I've created a simple extract of the current problem: how template specialization works:
template<typename T> class TestClass{
public:
// Sample constructor
TestClass(const char* name){
std::cout << "Created class " << name << std::endl;
}
};
// Doesn't add any functionalities, just used as an example
template<> class TestClass<int>{};
As expected, if I use the following:
TestClass<char> test = TestClass<char>("Test");
The file compiles, and the output is correct.
But if I use the following:
TestClass<int> specializedTest = TestClass<int>("Specialized Test");
The file doesn't compile, throwing the following error:
test.cpp: In function ‘int main()’:
test.cpp:50:69: error: no matching function for call to ‘TestClass<int>::TestClass(const char [17])’
test.cpp:50:69: note: candidates are:
test.cpp:47:18: note: TestClass<int>::TestClass()
test.cpp:47:18: note: candidate expects 0 arguments, 1 provided
test.cpp:47:18: note: TestClass<int>::TestClass(const TestClass<int>&)
test.cpp:47:18: note: no known conversion for argument 1 from ‘const char [17]’ to ‘const TestClass<int>&’
Question 1: Shouldn't the specialized class inherit the TestClass's members and functions? Because if it doesn't, it looks to me that I'm just creating a class and "masking" it as the base class. i.e. (in pseudocode)
class SpecializedTestClass{/* Add class code here */};
typedef SpecializedTestClass TestClass<int>;
If not, why not? It makes sense for me that, if you're specializing a class, all classes members/functions should be kept unless they are specialized.
Maybe I'm just mixing template with class inheritance.
Question 2: Is this the best approach to my problem? (Combine the functionalities of basic_string< unsigned char > and basic_string< char > so that the data is stored as unsigned char, but can be assigned from char using typecasts.)