#include <iostream>
#include <string>

#if 0
std::string operator"" _pre(const char* str, std::size_t size) {
    return "prefix_" + std::string(str, size);
}

int main() {
    std::string s = "hello"_pre;
    std::cout << s << std::endl;
    return 0;
}
#endif

constexpr long double operator"" _km(long double distance) {
    return distance * 1000;
}

int main() {
    long double distance = 12.34_km;
    std::cout << distance << " meters" << std::endl;
    return 0;
}

/* 
Yes, in this example, the keyword constexpr is used before the operator function
definition.

constexpr is a C++11 keyword that indicates that a function or variable can be
evaluated at compile-time and its value is constant, which means that it can be
used in situations where a constant expression is required, such as the size of 
an array or the value of a template parameter.

When you use constexpr on a function, the compiler will try to evaluate the 
function at compile-time if all of its arguments are constant expressions. If 
the function can be evaluated at compile-time, the program will be more efficient
because the computation will be done at compile-time, instead of runtime.

Using constexpr on the operator function ensures that the operator can be used in
constant expressions and its result will be a compile-time constant if the
argument passed to the operator is a constant expression. It is not necessary
in this example but it is a good practice to use it when you define operators,
you can use this keyword to make sure the function can be used in constant 
expressions, and it also signals to the compiler that the function is intended
to be used in such a way.
*/

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: