Khurshid
Khurshid

Reputation: 2724

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 ?

Upvotes: 1

Views: 457

Answers (2)

Stefano Falasca
Stefano Falasca

Reputation: 9097

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.

Upvotes: 0

doomster
doomster

Reputation: 171

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?

Upvotes: 2

Related Questions