When I'm writing a function in a template class how can I find out what my T is?
e.g.
template <typename T> ostream& operator << (ostream &out,Vector<T>& vec) { if (typename T == int) }
How can I write the above if statement so it works?
Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.
There is no difference. typename and class are interchangeable in the declaration of a type template parameter.
What is the syntax of class template? Explanation: Syntax involves template keyword followed by list of parameters in angular brackets and then class declaration. As follows template <paramaters> class declaration; 2.
There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.
Something like this:
template< class T > struct TypeIsInt { static const bool value = false; }; template<> struct TypeIsInt< int > { static const bool value = true; }; template <typename T> ostream& operator << (ostream &out,Vector<T>& vec) { if (TypeIsInt< T >::value) // ... }
Since C++11 we have std::is_same
:
if (std::is_same<T, int>::value) ...
It's implemented similar to the suggested trait TypeIsInt
suggested in the other answers, but with two types to be compared.
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