I’m frequently troubled by const correctness, and this seems to be no exception. Please advise me why the following code wont compile:
class string_token_stream
{
public:
typedef wchar_t* string_type;
string_token_stream(const string_type input_string)
: _input_string(input_string)
{
}
private:
const string_type _input_string;
};
int main(int argc, char **argv)
{
const wchar_t *str = get_a_string_somewhere();
string_token_stream sts(str);
// ^------ Compile-time error C2664.
return 0;
}
The error given is:
error C2664: 'string_token_stream::string_token_stream(const string_token_stream::string_type)' : cannot convert parameter 1 from 'const wchar_t *' to 'const string_token_stream::string_type'
1> Conversion loses qualifiers
I’m compiling on Visual C++ 2010 Express. Additional compile/linker options available upon request.
When you write
const string_type input_stringtheconstis ignored for typedef. So you are trying to convertconst wchar_t*to awchar_t*.If you change
typedef wchar_t* string_type;totypedef const wchar_t* string_type;it should compile.const string_type input_stringwould look likewchar_t *const input_stringwhereas you expectedconst wchar_t*. You can see this by changingconst wchar_t *strtowchar_t *const strand it will also work.