Home > OS >  Default value in constructor parameter based on template type
Default value in constructor parameter based on template type

Time:01-16

I have a class as follows

typename <int len, bool is_internal=false>
class MyClass
{
    int var;
    char* buffer;

    MyClass(int v, char* buff)
    {/* some logic that initializes buffer */}
};

What i want is that when in_internal is true, the class constructor to not require the value of buffer in arguments, but make sure that is provided when is_internal is false.

I can do it with is_internal being a class member, but it creates a lot of code duplication in constructors, and i think there must be a cleaner way of doing this using templates or constexpr, and have things in compile time managed by the compiler. I also want the destructor to unallocate the buffer if is_internal is true.

Edit - this is something i wish for but in a neat way to be taken care of in compile time-

MyClass(int v, char* buff = nullptr)
{
    if(is_internal == true)
      assert(buff==nullptr);
    else
      assert(buff != nullptr);
    // rest of the common code.
}

CodePudding user response:

You don't have to create 2 complete constructors. You can use delegate constructor, like this:


#include <type_traits>

template<int len, bool is_internal=false>
class MyClass
{
    int var;
    char* buffer;

public:
    MyClass(int v, char* buff)
    {/* some logic that initializes buffer */}

    template<bool ii = is_internal>
    MyClass(std::enable_if_t<ii, int> v) : MyClass(v, nullptr) {}
};

int main()
{
    MyClass<10> a(5, nullptr);
    MyClass<20, true> b(8);
    //MyClass<30> c(9); // Error
}

CodePudding user response:

Use if constexpr

MyClass(int v, char* buff = nullptr)
{
    if constexpr(is_internal)
    {
      assert(buff==nullptr);
    }
    else
    {
      assert(buff != nullptr);
    }
}
  • Related