1

I want to define default value for my templated container class in the template.

// Example program
#include <iostream>
#include <string>

template <typename T, T TDefault>
class Thing
{
    T value;
    public:
    Thing(T p_value = TDefault):value(p_value) {}
    
    void print()
    {
        std::cout << value << "\n";
    }
    
};

int main()
{
    // This works
    Thing<int, 42> thing;

    thing.print();

    // is there a way to make this work?
    Thing<std::string, std::string("Hello, World!")> thing2;

    thing2.print();
}

I feel like I'm missing something very obvious ... this should be possible, right?

http://cpp.sh/3gnwe


Basically I just want to make a container class that I can define the default value for when I define it. Instead of having to give a value for it every time I call the constructor.


Yeah I found a neat way around it, I won't post it here because it's not in line with the strict rules of questions and answers of this site.

0xbaadf00d
  • 2,535
  • 2
  • 24
  • 46
  • Hm, it appears it's not possible. I need to do this differently https://stackoverflow.com/questions/4104147/why-cant-template-non-type-parameters-be-of-class-type/4105138 – 0xbaadf00d Sep 07 '21 at 08:23
  • only interger including enum and point can use as none type template parameter – HongluWong Sep 07 '21 at 08:25

0 Answers0