Fabian Knorr
Fabian Knorr

Reputation: 3184

User-defined literals as variadic templates

GCC 4.7.2 seems to have variadic-char-templated literal operators only implemented for numbers:

template<char... chars>
constexpr size_t operator "" _size() { return sizeof...(chars); }

int main()
{
    std::cout << 42_size;    // (1) works
    std::cout << "foo"_size; // (2) does not
}

Upvotes: 2

Views: 728

Answers (1)

Konstantin Vladimirov
Konstantin Vladimirov

Reputation: 6999

2.14.8.5 of C++11 standard declares

If L is a user-defined-string-literal, let str be the literal without its ud-suffix and let len be the number of code units in str (i.e., its length excluding the terminating null character). The literal L is treated as a call of the form operator "" X (str, len)

So rewrite your code as:

#include <iostream>

// (1)
template<char... chars>
constexpr size_t operator "" _size() { return sizeof...(chars); }

// (2)
constexpr size_t operator "" _size( const char* str, size_t sz ) { return sz; }

int
main(void)
{
  std::cout << 42_size << std::endl;    // (1)
  std::cout << "foo"_size << std::endl; // (2)

  return 0;
}

To explicitly specify correct form for (2)

Upvotes: 3

Related Questions