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);
.
Template in C++is a feature. We write code once and use it for any data type including user defined data types.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With