mardi 24 novembre 2015

try to do a static assertion on a string if possible or fallback to a runtime check when it's not

I have a class named databaseManager that can open protected and shared database. You can know that a database is protected if it's name starts with a "#". I also have two methods:

  • openProtectedDatabase(QString name) (private method)
  • openSharedDatabase(QString name) (public method)

since 99.99% of the time the user is going to use openSharedDatabase like that:

openSharedDatabase("I_m_a_database")

I want in this specific case to check at compile time that he has the right to do it (understand no "#" at the beginning of the string). so I can throw an error immediately.

Here is what I started to do:

bool DatabaseManager::isDatabaseProtected(QString name) {
    return name[0] == '#';
}

CollaoDatabase &DatabaseManager::openSharedDatabase(QString name){

//if a static assertion is possible
//static_assert(static_assertion_possible(name) && isDatabaseProtected(name), "this database name is protected")

//run time check 
if (isDatabaseProtected(name)) {
    qWarning() << name + " is a protected database";
    return nullptr;
}

return openProtectedDatabase(name);
}

Aucun commentaire:

Enregistrer un commentaire