Rohan Uprety
Rohan Uprety

Reputation: 61

decltype and auto feature in C++11

why both auto and decltype. cant auto only solve the purpose ?? what is output of this program Can someone give an example how auto and decltype is used in templates

 template <class A, class B>
auto findMin(A a, B b) -> decltype(a < b ? a : b)
{
    return (a < b) ? a : b;
}
  
// driver function to test various inference
int main()
{
    // This call returns 3.44 of doubale type
    cout << findMin(4, 3.44) << endl;
  
    // This call returns 3 of double type
    cout << findMin(5.4, 3) << endl;
  
    return 0;
}

Upvotes: 0

Views: 403

Answers (2)

Gonen I
Gonen I

Reputation: 6107

Both auto and decltype let the compiler deduce a type without you explicitly writing what the type is, but there are some important differences between them:

auto defines the type of a variable according to its initializing value.

keep in mind that you don't always initialize values in the same line that you declare them in. Example :

int main() {
    auto a = 5;
    // auto b;  // compile error - can't use auto without an initializing value

    decltype(a) b;  // OK, can declare b to be the same type as a.
    b = 6; // then in the next line you can assign it an int
}

In template functions, auto alone is sufficient to let the compiler deduce the return type. However, you can also add decltype to auto to override the compiler deduced value. For Example:

template<class A, class B> auto add(A a, B b) -> decltype(b) {
    return a + b;
}

int main() {
    // sum will be double without the ->decltype(b) part in add, but int with it
    auto sum = add(5.0, 6); 
}

Upvotes: 1

aleck099
aleck099

Reputation: 437

You can't declare a lambda expression without using auto or std::function.

Every lambda expression has a different type, because their types are generated when they are declared.

auto l = [] (int a, double b) {
    return a > b ? a : b;
};

decltype can not do that.


Also I found an interesting thing:

Given int a; double b;, and the type of a > b ? a : b is always double regardless of whether a is greater than b or not.

Upvotes: 0

Related Questions