0

I was writing a program for hashtables. The hashtable has pairs. first is a string and second belongs to a template class.

Need to initialize the template class as a string to return a default value when looking up strings.

template<typename T>
struct default_value;
template<>
struct default_value<int> {
    static constexpr int value = 0;
};

template<>
struct default_value<double> {
    static constexpr double value = NULL;
};

template<>
struct default_value<float> {
    static constexpr float value = NULL;
};

template<>
struct default_value<string> {
    static constexpr string_view value{""};
};

Currently, I am getting an error when I do the above for the string. I understand I cannot use constexpr for string and so I decided to use string_view. I have imported string_view already

parktomatomi
  • 3,851
  • 1
  • 14
  • 18
th0rin
  • 13
  • 3
  • 1
    Try `char *` type. – ABacker Nov 21 '21 at 07:30
  • `static constexpr double value = NULL;`: no, no, no, no... The macro `NULL` should not be used in C++; use `nullptr` instead; this way the compiler would have yielded an error for the this nonsensical line: You're initializing a number with a constant reserved for pointers; If you indeed need to pull this stunt, you should use `reinterpret_cast` to indicate this is done on purpose, but in this scenario you shouldn't. You could btw provide a reasonable default with `template struct default_value { static constexpr T value {}; };`, i.e. use the default initializer(covers numbers). – fabian Nov 21 '21 at 08:42
  • Is the assumption correct that `string_value` in the last 2 sentences of the question should be `string_view`? Since C++20 the default string constructor is `constexpr` btw. – fabian Nov 21 '21 at 08:46
  • Why do you need a default value? `std::unordered_map` works without one. – HolyBlackCat Nov 22 '21 at 18:27
  • I think what you're seeing is that you can't implicitly assign a `string_view` to a `string`, e.g. `string x = string_view { "..." };`. This question asks why: https://stackoverflow.com/q/47525238/1863938 – parktomatomi Nov 22 '21 at 18:33

0 Answers0