Reputation: 17306
I want to have a class that stores a pair of variables of different types, but I need to pass the zero or null defaults for the variables as template parameters. I can do so for int or doubles, but how do I do so for string? I know that that c++ currently does not have string parameters, but what are the laternative designs. I need something like this:
#include <iostream>
#include <string>
using namespace std;
template <typename atype, typename btype, atype anull, btype bnull>
class simpleClass {
public:
atype var1;
btype var2;
simpleClass<atype, btype, anull, bnull> *parent; // pointer to parent node
simpleClass(); ~simpleClass();
};
template <typename atype, typename btype, atype anull, btype bnull>
simpleClass<atype, btype, anull, bnull>::simpleClass() { var1 = anull; var2 = bnull;
parent = NULL; }
template <typename atype, typename btype, atype anull, btype bnull>
simpleClass<atype, btype, anull, bnull>::~simpleClass() {}
int main() {
simpleClass<string, int, "", 0> obj;
obj.var1 = "hello";
obj.var2 = 45;
cout << obj.var2;
return 0;
}
compiling this, I get
error: ‘struct std::string’ is not a valid type for a template constant parameter
Upvotes: 2
Views: 648
Reputation: 146968
You cannot pass non-integral types as template parameters, except for pointers and references. The best behaviour you could hope for is to pass a function which returns a "default" value for atype
and btype
.
Upvotes: 4