Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Usage of if constexpr in template

I am trying to understand the utility of if constexpr and want to know if there is any utility in using it in this way.

template<bool B>
int fun()
{
    if constexpr (B)
        return 1;
    return 0;
}

Is this function changed at all by using if constexpr instead of a regular if? I assume the performance would be the same. My understanding of templates is that the outcome of the if statement is already known at compile time so there is no difference.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Utility of constexpr?

A trivial example… if you write the following function

template <typename T>
auto foo (T const & val)
{
   if ( true == std::is_same_v<T, std::string>> )
      return val.size()
   else
      return val;
}

and call it with an integer

foo(42);

you get a compilation error, because the instruction

val.size();

has to be instantiated also when val is an int but, unfortunately, int isn’t a class with a size() method

But if you add constexpr after the if

// VVVVVVVVV
if constexpr ( true == std::is_same_v<T, std::string>> )
   return val.size()

now the return val.size(); instruction is instantiated only when T is std::string, so you can call foo() also with arguments without a size() method.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading