llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[clang-tidy] readability-use-std-min-max generates invalid code for string, where bare `size_type` is used

Open e-kwsm opened this issue 4 months ago • 3 comments

clang-tidy 22.1.8

#include <string>

void f(const std::string &s, unsigned &n) {
  if (s.size() > n)
    n = s.size();
}

clang-tidy --checks=readability-use-std-min-max --fix a.cpp rewrites the function body as follows

  n = std::max<size_type>(s.size(), n);

which does not compile since size_type is unknown; the correct fix is

  n = std::max<decltype(s.size())>(s.size(), n);
  // or std::string::size_type, or size_t?

https://godbolt.org/z/4oYsddq6d

e-kwsm avatar Jul 10 '26 10:07 e-kwsm

@llvm/issue-subscribers-clang-tidy

Author: Eisuke Kawashima (e-kwsm)

clang-tidy 22.1.8
#include &lt;string&gt;

void f(const std::string &amp;s, unsigned &amp;n) {
  if (s.size() &gt; n)
    n = s.size();
}

clang-tidy --checks=readability-use-std-min-max --fix a.cpp rewrites the function body as follows

  n = std::max&lt;size_type&gt;(s.size(), n);

which does not compile since size_type is unknown; the correct fix is

  n = std::max&lt;decltype(s.size())&gt;(s.size(), n);
  // or std::string::size_type, or size_t?

<https://godbolt.org/z/4oYsddq6d>

Library-free (but might not be a faithful reduction):

struct B {
protected:
    typedef unsigned long bsize;
};

struct S : B {
    typedef typename B::bsize size_type;
    size_type size() const;
};

void f(const S &s, unsigned &n) {
  if (s.size() > n)
    n = s.size();
}

https://godbolt.org/z/d8GovTd7s

chrchr-github avatar Jul 10 '26 11:07 chrchr-github

I’d like to work on this

xxxxbc avatar Jul 10 '26 15:07 xxxxbc