I have a class with a static const variable that I need to initialize differently depending on the variable type in the template parameter. Is there a way to do this without specialization?
In my header file I have:
template<class Item>
class CircularQueue {
public:
static const Item EMPTY_QUEUE;
...
Attempting to initialize it in the .cpp file:
template<typename Item> const Item CircularQueue<Item>::EMPTY_QUEUE = Item("-999");
I'd like it to initialize to -999 whether it's an int, double, or string. However, in the code above I get a "cast from 'const char' to 'int' loses precision [-fpermissive]" error.
Providing an example of using a separate helper class that can be specialized, instead of having to specialize this entire template class, since you mentioned you'd like to see an example of this approach.
Just declare a separate template class that sets the default value, and specialize it for std::string
.
template<class Item> class defaultItem {
public:
static constexpr Item default_value() { return -999; }
};
template<> class defaultItem<std::string> {
public:
static constexpr const char *default_value() { return "-999"; }
};
You don't have to use the constexpr
keyword, if your C++ compiler is not of a recent vintage. You can also define the same specialization for a const char *
, rather than a std::string
, if needed.
Then, your main class simply defines EMPTY_QUEUE
as:
template<typename Item>
const Item CircularQueue<Item>::EMPTY_QUEUE =
defaultItem<Item>::default_value();