0

I have the following C++ code to test our perfect forwarding used in delegation of arguments to constructors for objects of different types:

#include <iostream>

// THIS CLASS TAKES 2 ARGUMENTS.
struct A {
    A(int i, int j) {
        i = i;
        j = j;
    }

    int i;
    int j;
};

// THIS CLASS TAKES 3 ARGUMENTS.
struct B {
    B(int i, int j, int k) {
        i = i;
        j = j;
        k = k;
    }

    int i;
    int j;
    int k;
};

// THIS CLASS IS A VARIANT-LIKE DELEGATOR
// WHOSE FIRST ARGUMENT IS THE TYPE TAG,
// AND THE REST ARE FORWARDED TO THE CORRESPONDING CLASS.
struct Delegator {
    enum class Type : int {
        CLASS_A,
        CLASS_B
    };

    union {
        A a;
        B b;
    };

    template <typename... Args>
    Delegator(Delegator::Type type, Args... args) {
        type_ = type;

        if (type_ == Delegator::Type::CLASS_A) {
            new (&a) A(std::forward(args...));
        } else if (type_ == Delegator::Type::CLASS_B) {
            new (&b) B(std::forward(args...));
        } else {
            throw std::invalid_argument("Delegator constructor: "
            "forwarded arguments does not match any of its member type constructors!");
        }
    }


private:
    Delegator::Type     type_;
};

int main() {
    // THIS IS GOOD.
    Delegator delegator(Delegator::Type::CLASS_A, 1, 2);

    // THIS IS BAD.
    Delegator delegator(Delegator::Type::CLASS_A, 1, 2, 3, 4);
}

I was wondering -- what is the current state of error messaging with C++ when dealing with these types of cases? Is there anything comparable to the (syntax-error) facility provided with Scheme so that users of an object can get a better error message upon improper usage? I don't care what standard of C++ is used -- I just want to know if it's currently possible to tweak the error diagnostic messages of C++.

Can the programmer do anything about these long templated-code error messages for future users? Or is it all in the hands of the compiler?

CinchBlue
  • 6,046
  • 1
  • 27
  • 58

0 Answers0