vendredi 24 avril 2020

User defined literals which only differ in the return values

This is what I want to achieve: I have two user defined literals with one taking a long double value and returning a slope, and the other also taking a long double value and returning a humidity. Now I want to use both UDLs in one scope. Unfortunately, in both cases the unit is 'percentage'.

struct slope
{
    long double val;
};
slope operator ""_perc(long double v)
{
    slope s = {v};
    return s;
}

struct humidity
{
    long double val;
};
humidity operator ""_perc(long double v)
{
    humidity h = {v};
    return h;
}

void func(void)
{
    slope s(0.0_perc);
    humidity h(0.0_perc);
}

This is not possible since the signatures of two functions cannot only differ in the return type. We could use namespaces:

namespace slp
{
    slope operator ""_perc(long double v)
    {
        slope s = {v};
        return s;
    }
}
namespace hum
{
    humidity operator ""_perc(long double v)
    {
        humidity h = {v};
        return h;
    }
}

but I dare state that user defined literals only make sense when used 'unqualified'. We do not want to use them this way:

void func(void)
{
    slope s(slp::operator"" _perc(0.0));
    humidity h(hum::operator"" _perc(0.0));
}

Since both UDLs shall be used in the same scope, we cannot use 'using' because of the ambiguity it creates:

using namespace slp;
using namespace hum;

or

using slp::operator ""_perc;
using hum::operator ""_perc;

So I am stuck. Is there any - preferably elegant - way to achieve what I want?

Aucun commentaire:

Enregistrer un commentaire