0

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?

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
Troskyvs
  • 7,537
  • 7
  • 47
  • 115
  • It only sports the widest type for each kind. – bolov Sep 21 '22 at 08:01
  • Even if the operator uses an `unsigned long long` parameter, it can still return an int (or whatever you like). Just like [chrono::""min](https://en.cppreference.com/w/cpp/chrono/operator%22%22min) returns minutes. – BoP Sep 21 '22 at 11:54

1 Answers1

1

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).

Jarod42
  • 203,559
  • 14
  • 181
  • 302