Search code examples
c++stringtemplatescstringlpcstr

How to use Templates when working with std::strings and c-style strings?


I was just messing around with templates, when I tried to do this:

template<typename T> void print_error(T msg)
{
#ifdef PLATFORM_WIN32
    ::MessageBox(0, reinterpret_cast< LPCSTR >(msg), "Error", MB_ICONERROR|MB_OK);
#else
    cout << msg << endl;
#endif /* PLATFORM_WIN32 */
}

Of course this obviously will not work if you pass an std::string as T. Because a string can't be cast to a char*, But can this function be coded in a way that it will allow me to pass both a c-style char* array and a c++ std::string as the parameters, and convert them to LPCSTR ?


Solution

  • You can use function overloading:

    void print_error(char const* msg);
    void print_error(std::string const& msg);
    ...