Skip to content

Instantly share code, notes, and snippets.

@thekvs
Created March 19, 2013 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thekvs/5194368 to your computer and use it in GitHub Desktop.
Save thekvs/5194368 to your computer and use it in GitHub Desktop.
Deduce return type through decltype
// compiles with gcc 4.7+:
// g++ -Wall -W -g -std=c++11 test.cpp -o /tmp/test
//
// ... and clang 3.0+:
// clang++ -W -g -std=c++11 test.cpp -o /tmp/test
#include <iostream>
#include <typeinfo>
template<class T, class U>
auto mul(T x, U y) -> decltype(x*y)
{
return x*y;
}
int
main()
{
auto result1 = mul(1.5, 2);
std::cout << typeid(result1).name() << ": " << result1 << std::endl;
auto result2 = mul(3, 2);
std::cout << typeid(result2).name() << ": " << result2 << std::endl;
auto result3 = mul(1.5f, 2);
std::cout << typeid(result3).name() << ": " << result3 << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment