Pranit Kothari
Pranit Kothari

Reputation: 9841

Why std::string reference cannot take char*?

I have simple code.

template<typename T>
class NamedObject{
public:

    NamedObject(std::string& name, const T& value):nameValue(name), objectValue(value)
    {

    }

private:
    std::string& nameValue;
    const T objectValue;
};

int main(int argc, char* argv[])
{
    NamedObject<int> no1("Smallest Prime Number",2);//error
    NamedObject<int> no2(std::string("Smalledst Prime Number"),2);//works

    return 0;
}

When I make first parameter as non refrence, both no1 and no2 object gets created. But when I keep reference Visual Studio compiler gives following error,

Error 1 error C2664: 'NamedObject::NamedObject(std::string &,const T &)' : cannot convert parameter 1 from 'const char [22]' to 'std::string &' c:\users\pkothari\documents\visual studio 2008\projects\stackoflw\stackoflw\stackoflw.cpp 36

If char * can be casted to std::string, why not to std::string& ? Is there any way to make it work?

Upvotes: 1

Views: 442

Answers (1)

R Sahu
R Sahu

Reputation: 206607

NamedObject<int> no2(std::string("Smalledst Prime Number"),2);//works

That should not work in a standard compliant compiler. It is supported in MS Visual Studio C++ even though it is not standard C++.

Neither of the following calls should work when the expected argument is std::string&.

NamedObject<int> no1("Smallest Prime Number",2);
NamedObject<int> no2(std::string("Smalledst Prime Number"),2);

Both of them should work when the argument type is std::string or std::string const&.

Upvotes: 2

Related Questions