Search code examples
c++templatestypeid

Errors when trying to return variables in template c++


So im trying to get the contents of the clipboard in Windows, and as it can be any type Im using a template to get it, but when trying to build, Visual Studio 2013 RC sends this errors:

Error   1   error C2440: 'return' : cannot convert from 'char *' to 'double'
Error   2   error C2440: 'return' : cannot convert from 'double' to 'char *'    
Error   3   error C2440: 'return' : cannot convert from 'int' to 'char *'   
Warning 4   warning C4244: 'return' : conversion from 'double' to 'int', possible loss of data    
Error   5   error C2440: 'return' : cannot convert from 'char *' to 'int'

Heres the code:

template<typename tn>
tn GetClipboardContents()
{
    HANDLE h_clip;
    double d_clip;
    int i_clip;
    char* str_clip;
    if (OpenClipboard(NULL))
    {
        h_clip = GetClipboardData(CF_TEXT);
        if (typeid(tn).name() == "double")
        {
            d_clip = atof((char*)h_clip);
        }else if (typeid(tn).name() == "int"){
            i_clip = atoi((char*)h_clip);
        }else{
            str_clip = (char*)h_clip;
        }
        CloseClipboard();
    }

    if (typeid(tn).name() == "double")
        return d_clip;
    else if (typeid(tn).name() == "int")
        return i_clip;
    else
        return str_clip;
}

Thanks in advance.


Solution

  • You've got multiple return paths which return different types. You'll need to use template overloading, something along the lines of:

    template <typename tn>
    tn GetClipboardContents();
    
    
    template <>
    double GetClipboardContents<double>()
    {
        // Add double implementation here
    }
    
    template <>
    int GetClipboardContents<int>()
    {
        // Add int implementation here
    }
    

    Repeat for other types