Home > Enterprise >  Why template chooses T equals int when implicity passed uint16_t?
Why template chooses T equals int when implicity passed uint16_t?

Time:12-11

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

enter image description here

debugger shows next expression enter image description here

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related