Implicit conversions

In the following program:

#include <iostream>
#include <vector>
#include <string>

template <typename T>void printValue(const T &s)
{
std::cout << s <<'\n';
}

class implicit_conv
{
public:
operator const char*() const{return m_string.c_str();}
operator int() const{return m_val;}

explicit implicit_conv(int val) : m_string(),m_val(val){}
explicit implicit_conv(std::string s): m_string(s),m_val(){}
private:
std::string m_string;
int m_val;
};

int main (int , char* )
{
printValue(implicit_conv(1)); // conversion to int but why?
printValue(implicit_conv("test")); // conversion to int but why?
std::vector<implicit_conv> vec(10,1); // no error but why?
return 0;
}

Why does the compiler choose the int() conversion when it comes to

std::cout << s <<'\n';

with s of type implicit_conv?
why doesn't the compiler complain for the implicit conversion necessary in the following row?

std::vector<implicit_conv> vec(10,1); // no error but why?
Last edited on
You're apparently using a non-standard-compliant compiler.
In g++, std::cout << s <<'\n'; will not compile for T=implicit_conv, nor will the line that defines the vector compile. There should be no conversion to int going on in the two calls to printValue.
Topic archived. No new replies allowed.