I have the following function template
template<typename T>
T foo(){
if(std::is_same<T,int>::value){
return 1;
}
if(std::is_same<T,std::string>::value){
return "Hello";
}
}
I want to apply it like this:
int main(){
std::cout << foo<int>() << std::endl; // 1
std::cout << foo<string>() << std::endl; // "Hello"
}
If I try to compile my template the compiler throws the following error:
error: cannot initialize return object of type 'int' with an lvalue of type 'const char [6]'
.
If I remove the second if
statement everything compiles fine and I get the correct output therefore I guess the comparison std::is_same<T,int>::value
works as intended.
It seems like the Compiler detects the type of T
, checks if all return
statements match it and throws the error because an std::string
is not implicitly castable to int
.
Has anyone a solution or another workaround to satisfy my intention?
EDIT
To explain my intention: I am writing a wrapper class for a database cursor class. As these cursors are usually defined it has several member functions like getInt()
or getString()
. My idea was to implement a generic get<T>()
that uses the corresponding cursor member function that depends on T
.