Home > Mobile >  Force compile time check for correct object instantiation
Force compile time check for correct object instantiation

Time:01-15

How do I force the compiler to give errors if the user instantiates an object of some class incorrectly?

For example:

Polynomial a("x^2   2x   1"); //this is a valid Polynomial object

Polynomial b("3xy   2 - 5/z"); //this is not valid, force compiler error

static_assert seems to not work with function arguments and templates seem to not work with strings. If it's not possible to do this at compile-time, what are good ways to do this at run-time?

CodePudding user response:

I did read and read your question and comments and maybe I am confused what you want but why simple solution like that does not suit you:

#include <iostream>
struct Polynomial {
    const char* str;

    constexpr Polynomial(char const* arg) 
        : str(arg) {
        // if check fails constructing constexpr Polynomial we get compile error
        // if check fails with dynamic runtime Polynomial then it does throw
        if (arg[0] != 'b') throw 42; 
    }
};

int main() {
    // should compile as first character is 'b'
    constexpr Polynomial a("bar");
    const char* foo = "foo";
    try {
        // should throw as first character is not 'b'
        Polynomial b(foo);
    } catch (...) {
        std::cout << "Q.E.D." << std::endl;
    }
} 

This AFAIK worked already in C 14.

  •  Tags:  
  • Related