简体   繁体   中英

compile-time check with const char* (nullptr)

I have a template class that takes a string literal as parameter. The code works fine - but I've got one question, whether it is possible to use compile-time check to skip the generating of if (S) or else block body at all? (Something like the __if_exists or #if, traits, etc). I understand that I could have a specialized A<nullptr> that defines a different print() function, but also want to know whether there's other (more simple) ways of doing this. Thanks!

template<char const* S = nullptr>
class A
{
public:
    void print()
    {
        if (S)
            cout << S << endl;
        else
            cout << "nullptr" << endl;
    }
};

In your case, can't you set the default value of S as "nullptr" or any other constant string? Of course, this works when you don't actually need S to be NULL, but it will skip the if check.

add a function,

constexpr const char* getStr(){
   return S? S : "null";
}

then it becomes,

void print(){
   std::cout << getStr() << std::endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM