Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to query if(T==int) with template class

Tags:

c++

templates

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?

like image 590
Meir Avatar asked Jun 14 '09 08:06

Meir


People also ask

What does template <> mean in C++?

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.

What is the difference between template typename T and template T?

There is no difference. typename and class are interchangeable in the declaration of a type template parameter.

What is the syntax of template class?

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.

How will you restrict the template for a specific datatype?

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.


2 Answers

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)     // ... } 
like image 198
CB Bailey Avatar answered Sep 19 '22 23:09

CB Bailey


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.

like image 34
leemes Avatar answered Sep 19 '22 23:09

leemes