Does c++14 literal operator only support long double and unsigned long long type?

351 Views Asked by At

I've tried this code:

#include <iostream>
using namespace std;
constexpr int operator"" _w(int d) { return d; }
struct Watt {
    int d;
    Watt(int _d) : d(_d) {}
};
Watt operator "" _watt(int d) { return Watt(d); }

int main() {
    Watt w1 = 17_w;
    cout << w1.d << endl;
    return 0;
}

Compile with clang++ 14, it gives:

<source>:3:29: error: invalid literal operator parameter type 'int', did you mean 'unsigned long long'?
constexpr int operator"" _w(int d) { return d; }
                            ^~~~~
<source>:8:24: error: invalid literal operator parameter type 'int', did you mean 'unsigned long long'?
Watt operator "" _watt(int d) { return Watt(d); }
                       ^~~~~
<source>:11:17: error: no matching literal operator for call to 'operator""_w' with argument of type 'unsigned long long' or 'const char *', and no matching literal operator template
    Watt w1 = 17_w;

Just wish to know, whether c++14's literal operator limits to support certain restricted data types? Is int type feasible here in my code? If yes, how to fix it?

1

There are 1 best solutions below

0
Jarod42 On

From Literal_operators

int is not part of allowed parameters lists:

  • ( const char * ) (1)
  • ( unsigned long long int ) (2)
  • ( long double ) (3)
  • ( char ) (4)
  • ( wchar_t ) (5)
  • ( char8_t ) (6) (since C++20)
  • ( char16_t ) (7)
  • ( char32_t ) (8)
  • ( const char * , std::size_t ) (9)
  • ( const wchar_t * , std::size_t ) (10)
  • ( const char8_t * , std::size_t ) (11) (since C++20)
  • ( const char16_t * , std::size_t ) (12)
  • ( const char32_t * , std::size_t ) (13)

You have to use unsigned long long int instead (as suggested by your compiler).