Me myself and I
Me myself and I

Reputation: 4060

Why doesn't this template code work?

They told me to use templates to find the sum. Why doesn't this work? Thanks.

template <typename A, typename B, typename C>
auto add(A a, B b, C c = a + b) -> decltype(c) {
    return c;
}

I thought C++11 said you can use the arguments after they are declared. Why doesn't this work then?

Upvotes: 4

Views: 166

Answers (1)

Pubby
Pubby

Reputation: 53037

You can't use arguments as the value of defaults. Also, template type deduction doesn't work that way.

Just write it like this:

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

And hope C++ gets return type deduction soon.

Upvotes: 3

Related Questions