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

Why template chooses T equals int when implicity passed uint16_t?

I have next snippet

class Mapper { //not templated!
...
template<class T>
static QList<quint16> toPduValue(T value)
{
    constexpr quint8 registersPerT = sizeof(T) / sizeof(quint16);

    return buildPduValue((registersPerT < 1) ? (quint16) value : value);
}


template<class T>
static QList<quint16> buildPduValue(T value)
{
...
}
...
}

But when to toPduValue passed bool, and then to buildPduValue passed (quint16) value buildPduValue specializes like <int>?

callstack

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

enter image description here

debugger shows next expression
enter image description here

>Solution :

The type of your ternary expression is int. You can verify this by trying to compile this code and looking carefully at the error message:

#include <stdint.h>
char * foo = (2 < 3) ? (uint16_t)2 : (bool)1;

The error message will be something like:

error: invalid conversion from ‘int‘ to ‘char*’

You could just apply a cast to your ternary expression to cast it to the specific type you want.

Or you could ensure that both possible values of the ternary expression have the same type, so that the overall expression will have the same type.

Or you could use a if statement instead of a ternary expression.

Note that your ternary expression can only have one type; it doesn’t have a different type depending on which case was evaluated.

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