Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class template for numeric types

Tags:

c++

templates

How do I write a class template that accepts only numeric types (int, double, float, etc.) as template?

like image 689
djWann Avatar asked Jan 12 '13 14:01

djWann


People also ask

What is class template example?

A class template can be declared without being defined by using an elaborated type specifier. For example: template<class L, class T> class Key; This reserves the name as a class template name.

What is the difference between class template and template class?

A class template is a template that is used to generate classes whereas a template class is a class that is produced by a template.

What is a template class?

Definition. As per the standard definition, a template class in C++ is a class that allows the programmer to operate with generic data types. This allows the class to be used on many different data types as per the requirements without the need of being re-written for each type.

What Is syntax of class template?

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.


1 Answers

You can use the std::is_arithmetic type trait. If you want to only enable instantiation of a class with such a type, use it in conjunction with std::enable_if:

#include <type_traits>  template<     typename T, //real type     typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type > struct S{};  int main() {    S<int> s; //compiles    S<char*> s; //doesn't compile } 

For a version of enable_if that's easier to use, and a free addition of disable_if, I highly recommend reading this wonderful article on the matter.

In C++, the technique described above has a name called "Substitution Failure Is Not An Error" (most use the acronym SFINAE). You can read more about this C++ technique on wikipedia or cppreference.com.

As of C++20, concepts make this much easier and don't spoil the interface:

#include <concepts>  template<typename T> concept arithmetic = std::integral<T> or std::floating_point<T>;  template<typename T>   requires arithmetic<T> struct S{}; // Shorthand: template<arithmetic T> struct S {}; 

Do note that there are many user types meant to be used arithmetically as well, though, so a more general concept that covers the operations you're looking for instead of the types you're looking for would be preferable in a generic interface.

like image 112
chris Avatar answered Oct 14 '22 08:10

chris