Re: Why only integer consts can be defined in the class?
On 31 Okt., 17:41, Adam Badura <abad...@o2.pl> wrote:
Before the rule was changed to allow in class initialisers for static
const integral types the above code was written by subverting enums:
struct X {
enum {arraysize = 10};
mytype array[arraysize];
}
And what was wrong with using enums?
Actually two things:
1) The obvious one is the lack of type safety. Consider
a definition of std::basic_string<>::npos as enum:
template<class charT, class traits = char_traits<charT>,
class Allocator = allocator<charT> >
class basic_string {
typedef Allocator allocator_type;
typedef typename Allocator::size_type size_type;
// This is the official way:
//static const size_type npos = -1;
// Now consider a pre-C++98 compiler:
enum {npos = static_cast<size_type>(-1)};
};
void foo(const std::string& s) {
typedef std::string s_t;
s_t s2(s, 2, s_t::npos); // [1]
s_t::size_type idx = s2.find("Boo");
s2.erase(idx, s_t::npos); // [2]
}
At [1] and [2] nearly any reasonably configured compiler
will give you a type-mismatch warning and to get rid of
these, you would need to write code like this (I deliberatly
omitted the natural calling choices of calling the
corresponding functions which would not provide the
second argument at all):
void foo(const std::string& s) {
typedef std::string s_t;
s_t s2(s, 2, static_cast<s_t::size_type>(s_t::npos));
s_t::size_type idx = s2.find("Boo");
s2.erase(idx, static_cast<s_t::size_type>(s_t::npos));
}
2) A more subtle one is related to the question, which
linkage such enumerators do have, see:
http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#216
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]