简体   繁体   中英

std::basic_string::npos declaration in C++11

the basic_string class has npos which declared as static const. Why it declares as static const since C++11, why not simple as:

class basic_string{ 
  ................................

 enum: size_type { npos = static_cast<size_type>(-1) };
.........................>
};

???

which is good, static const or enum ?

There is a good reason not to do that, the enumeration creates a new type which will at least cause changes when resolving overloads or instantiating templates.

That said, I believe that you can actually declare and define class-static constants in the class definition, or is there some exception to that rule when the class is a template?

The two solutions are pretty much the same. The so called enum hack was born because of compilers which didn't support for in class initialization, mostly. The differences are: you cannot take the address of the enum "variable"; the static const approach is type-safe. Now, in C++11 enum classes are indeed type safe (except you stick to enums).

Basically, then, the only difference is in the "address of" issue. But, when you define an enum class you are defining a type; you might well find it to be bad looking to define a type when what you need is a constant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM