Frode Lillerud
Frode Lillerud

Reputation: 7394

"User-defined literal operator not found"

I'm reading the CppCoreGuidelines Philosophy, and have found an example that I don't understand. (https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#S-philosophy)

The codeexample says;

change_speed(double s);   // bad: what does s signify?
// ...
change_speed(2.3);

change_speed(Speed s);    // better: the meaning of s is specified
// ...
change_speed(2.3);        // error: no unit
change_speed(23m / 10s);  // meters per second

My question is regarding the last line. I'm assuming that the guidelines recommends defining Speed like this;

typedef int Speed;

but in the final line in the example they are using m and s as part of the arguments. If I try the same I just get an error saying "user-defined literal operator not found".

How is this supposed to work?

Upvotes: 3

Views: 21263

Answers (1)

My question is regarding the last line. I'm assuming that the guidelines recommends defining Speed like this;

typedef int Speed;

Nope. They are expecting something like:

class Speed {
    double value;
public:
    ....
}

class Distance {
     double value;
public:
     ...
};

class Time {
     double value;
public:
     ....
};

Speed operator /(Distance d, Time t);

and a pair of user defined literal operators for Distance and Time

Distance operator "" _m(double);

Time operator "" _s(double);

There is a bug in the example though. It should be:

change_speed(23_m / 10_s);  // meters per second

Upvotes: 7

Related Questions