Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++ templates infer return type?

Tags:

c++

templates

I'm playing around with templates and I'm wondering if there's any way to make code like this work.

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

int something = foo (123);

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

I know that this would work if I this used 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'd like to know if it's possible to make the code return a double when used like this double x = foo (123); and an int when used like this int x = foo (123);.

like image 958
Irenej Marc Avatar asked Sep 28 '14 05:09

Irenej Marc


People also ask

Can templates be used for user defined data types?

Template in C++is a feature. We write code once and use it for any data type including user defined data types.

Why do we use templates in C?

A template is a simple yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types.

Are templates supported in C?

The main type of templates that can be implemented in C are static templates. Static templates are created at compile time and do not perform runtime checks on sizes, because they shift that responsibility to the compiler.

Is template a keyword in C?

C++ template is also known as generic functions or classes which is a very powerful feature in C++. A keyword “template” in c++ is used for the template's syntax and angled bracket in a parameter (t), which defines the data type variable.


1 Answers

One way to infer a return type (although it's unclear what you're going to use that for) is to use a templated conversion, e.g.

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: code untouched by compiler's hands.

like image 174
Cheers and hth. - Alf Avatar answered Sep 24 '22 02:09

Cheers and hth. - Alf