1

This program is not compiling. What's the problem?

#include<iostream>
#include<map>
using namespace std;

template<class T>class Data{
    string header;
    T data;
public:
    Data(string h, T d){header = h, data = d;}
    void WriteData()
    {
        cout<<header<<": "<<data<<endl;
    }
};


int main(int argc, _TCHAR* argv[])
{
    Data<int> idata("Roll", 100);

    Data<string>sdata("Name","Jakir");

    idata.WriteData();
    sdata.WriteData();
    return 0;
}

Showing the following errors.

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion) c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(679): could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<>(std::basic_ostream<_Elem,_Traits> &,const char *)' with [ _Elem=char, _Traits=std::char_traits ]

while trying to match the argument list '(std::ostream, std::string)' .....\maptest\mapt\mapt\mapt.cpp(16) : while compiling class template member function 'void Data::WriteData(void)' with [ T=int ]

2 Answers 2

9

It seems you forgot to:

 #include <string>

You cannot count on transitive inclusion of all the necessary header files because some other header like <iostream> may #include them.

If you are using std::strings, you should be #includeing the appropriate header (<string>) explicitly.

Overloads of operator << which accept an std::string are probably declared/defined in a header which is not #included by <iostream>.

Besides, avoid having using directives at global namespace scope such as this:

using namespace std;

They can easily lead to name clashes and it is normally regarded as a bad programming practice.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh my god. What a mistake I've made. Thanks a lot. It spoiled my 2 hours. thanks again.
@JakirHossain: We've all been there ;) Good luck with your project
2

T_char is incorrect type as argv should have a type for example char*

Correct source code is

#include<iostream>
#include<map>
#include<string>
using namespace std;

template<class T>class Data{
    string header;
    T data;
public:
    Data(string h, T d){header = h, data = d;}
    void WriteData()
    {
        cout<<header<<": "<<data<<endl;
    }
};


int main(int argc, char* argv[])
{
    Data<int> idata("Roll", 100);

    Data<string>sdata("Name","Jakir");

    idata.WriteData();
    sdata.WriteData();
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.