Question

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.

Was it helpful?

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

OTHER TIPS

A function cannot have two return statements, each with a different type, unless each has a valid converion to the return type of the function.

For example:

int foo (bool flag) {
    if (flag) return "hi";
    return -1;
}

The first return is invalid. Your template function has similar problems. For any given instantiation of the the tempalte function, you have a conversion problem for at least one of the other return values.

One way to fix this is with some kind of custom result object that can be initialized by any of the three types you are trying to return.

Another way to fix this is to specialize your template for each return type, so that each instance only returns the single valid type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top