Can C ++ templates infer the return type?

I am playing with templates and I am wondering if there is a way to make code like this work.

template <typename T>
T foo (int a)
{
  return a * 2;
}

int something = foo (123);

      

The problem is that the type cannot be inferred by the compiler.

I know it will work if I used it in the above case.

int a = foo <int> (123);

      

or even

template <typename T>
T foo (T a)
{
  return a * 2;
}
int a = foo (123);

      

EDIT: For clarification, I would like to know if it is possible to make the code return double when used like this double x = foo (123);

and int when used like this int x = foo (123);

.

+3


source to share


2 answers


One way to deduce the return type (although it's not clear what you're going to use this for) is to use a template conversion like

class foo
{
private:
    int a_;
public:
    template< class Return_type >
    operator Return_type () const
    { return a_*2; }

    foo( int const a ): a_( a ) {}
};

void bar()
{ int a = foo( 123 ); }

      



Disclaimer: The code is not touched by the hands of the compiler.

+3


source


Using type_traits

, you can do all this and more:



#include <type_traits>    

template<typename T = std::enable_if<std::is_arithmetic<T>::value>::type>
T foo(T a)
{
    return a * 2;
}

int main()
{
    auto bar = foo(1); //bar is an int
    auto car = foo(1.0) //car is a double
    auto star = foo(1.0f); //star is a float
}

      

-1


source







All Articles