C++:Decltype
lastmod 2015-09-11created 2015-03-193 edits
What is decltype
decltype also serves to cover for Auto and is used in many different ways. Most commonly, it is used to determine a function's return type at the time the function is declared. For example, suppose you create two or more variables with a Template, the two Template variable types are different from each other, and the function returns auto. Then Auto does not know what to return, and an error occurs. In such cases, Decltype is what you write to make it explicit.
To put it more precisely, Decltype means the compiler matches the data type of an expression.
The method below is used when the function's return type is auto and it is ambiguous with the template.
#include <iostream>
template<typename T, typename Y>
auto Add(T a, Y b) -> decltype (a + b)
{
return a + b;
}
int main(void)
{
std::cout << Add('1', 5) << std::endl;
std::cout << Add(std::string("안녕"), std::string("하삼?")).c_str() << std::endl;
std::cout << Add(1000, 0.1234) << std::endl;
return 0;
}
Alternative Function Syntax (->)
Putting decltype after it means the return type will be matched to a+ b. Try running it once and you will get the idea.