Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor that produces compile time errors depending on parameter values

Tags:

c++

I have a class C and want to do the following:

class C {
public:
    C(const size_t aa, const size_t bb) { // aa and bb are compile time constants
    // when aa + bb > 10 raise a compile time error
    }
private:
    size_t a;
    size_t b;
}

Constructor C::C should type check and reject any aa and bb values that are not known at compile-time and are not positive integers. If that check passes, the compiler should check their sum. If the sum is greater than 10, the compiler should reject the constructor call.

Is this doable (and how) using only ISO C++11, not relying on the specific compiler?

like image 934
foki Avatar asked Jul 21 '26 00:07

foki


1 Answers

At compile-time, what you are asking for is possible only with templates, eg:

template<size_t aa, size_t bb>
class C {
public:
    C() {
        static_assert(aa > 0, "aa must be > 0");
        static_assert(bb > 0, "bb must be > 0");
        static_assert((aa + bb) <= 10, "aa + bb must be <= 10");
    }
};
C<1, 2> c1; // OK
C<5, 6> c2; // compile error

Live Demo

Otherwise, at run-time, all you can do is throw an exception on bad input, eg:

#include <stdexcept>

class C {
public:
    C(const size_t aa, const size_t bb) : a(aa), b(bb) {
        if (aa == 0)
            throw std::runtime_error("aa must be > 0");
        if (bb == 0)
            throw std::runtime_error("bb must be > 0");
        if ((aa + bb) > 10) {
            throw std::runtime_error("aa + bb must be <= 10");
        }
    }
private:
    size_t a;       
    size_t b;
};
C c1(1, 2); // OK
C c2(5, 6); // runtime error

Live Demo

like image 184
Remy Lebeau Avatar answered Jul 22 '26 13:07

Remy Lebeau