tags:

views:

623

answers:

6

With a vector defined as std::vector<std::string>, Wondering why the following is valid:

if ( vecMetaData[0] != "Some string" ) 
{
    ...

But not this:

switch ( vecMetaData[1] )
{
    ...

Visual studio complains :

error C2450: switch expression of type 'std::basic_string<_Elem,_Traits,_Ax>' is illegal 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits, 1> _Ax=std::allocator 1> ] 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

+1  A: 

You can use switch only for basic datatypes (int, char etc.).

schnaader
+2  A: 

It is valid because the first will call the operator!= of std::string, which will accept a const char* as an argument. That, however, doesn't mean that std::string also has an operator some_integral_type() that will return a integral expression which switch needs.

Using operators in C++ does not necassary invoke the builtin meaning. Your code, for example, doesn't compare pointer values. It might invoke a user defined (in this case, the one of std::string) operator function.

Johannes Schaub - litb
+13  A: 

switch() needs an integral type (like int, char, ...)

string is not an integral type, neither does string have an implicit conversion to an integral type, so it can't be used in a switch statement

Pieter
A: 

The easiest alternative BTW is a std::map<std::string, boost::function> StringSwitch;

This lets you say StringSwitch["Some string"](arguments...)

MSalters
A: 

If you just want to check each thing in the vector, you could use the for_each standard library function (http://www.dinkumware.com/manuals/?manual=compleat&amp;page=algorith.html#for_each). Or if you want to act on a subset of possible values, use find_if (http://www.dinkumware.com/manuals/?manual=compleat&amp;page=algorith.html#find_if) to get iterators for the matching items and then use a loop or for_each to act on them.

Reed Hedges
A: 

neither of those are probably what you want anyhow... since I assume you want to use the std::string::compare function to do a string comparison