0

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;
    }
};
  • Yay. The simplest way is to turn on compiler optimizations. –  Oct 15 '13 at 06:48
  • Good answer, thanks :) I don't fully control the compiler options. In fact our compiler rejects even the code above (`if (nullptr)`) as "conditional expression is constant". – user2881294 Oct 15 '13 at 07:08
  • @userXXX Which compiler do you use, actually? –  Oct 15 '13 at 07:08
  • I use VC++ - but the one runs on our code server is something that I don't control. (I should have picked up a user name.. :)) – user2881294 Oct 15 '13 at 07:33
  • Indeed :) I understand. I'm not great at C++ and I don't knos if this should compile, but that's an interesting issue anyway. –  Oct 15 '13 at 07:43

2 Answers2

0

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.

asalic
  • 949
  • 4
  • 10
0

add a function,

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

then it becomes,

void print(){
   std::cout << getStr() << std::endl;
}
Zac Wrangler
  • 1,445
  • 9
  • 8
  • Thanks - the print/cout is just for demonstration, the actual code is more complex that this, adding a new function would still result in the same `if .. else ..` code block. – user2881294 Oct 15 '13 at 07:51