Chrispresso
Chrispresso

Reputation: 4061

How can I simulate decltype in a trailing-return-type before C++11?

If I have for instance this in C++11:

#include <iostream>

template <typename T1, typename T2>
auto add(T1 t1, T2 t2) -> decltype(t1 + t2)
{
    decltype(t1 + t2) val = t1 + t2;
    return val;
}

int main()
{
    double a = 12.5;
    int b = 4;
    std::cout << add(a, b) << std::endl; // prints 16.5
}

I can return a type that can be determined automatically by the compiler.

As I'm new to C++ and currently need to implement something like this in C++98, does anyone know how I would go about that?

Upvotes: 1

Views: 459

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

Commonly, in C++98/C++03, to keep things simple we did this manually:

#include <iostream>

template <typename R, typename T1, typename T2>
R add(T1 t1, T2 t2)
{
    R val = t1 + t2;
    return val;
}

int main()
{
    double a = 12.5;
    int b = 4;
    std::cout << add<double>(a, b) << std::endl;
    //              ^^^^^^^^
}

(live demo)

That this sucks a lot is precisely why decltype and trailing-return-types were added to the language.

Upvotes: 8

Related Questions