Answer the question
In order to leave comments, you need to log in
How to do different processing for different types in a function template?
Hello! Tell me how to implement using templates. At the moment, there are two functions that do almost the same job. In addition, the functions differ in the type of input data: one accepts only integer values, and the other only double. It would seem easy to combine them into one using a template, but there is a nuance. The fact is that depending on the type of data, you need to perform different actions on the data. The data comes from the hardware and is transmitted in integer form, and the program knows the conversion factor (1, 0.1, 0.01, etc.). However, some controls in the program allow you to set parameters in double format. Accordingly, I have two functions that, depending on the type of data, either apply multiplication by a coefficient or not. Also, why can't you directly apply the template - because input parameters are set to 2 controls at once - one accepts only integers, and the other accepts double. So you have to multiply where it is necessary, and where it is necessary to divide. For example, the slider accepts only integers and its values from 0 to 100, and the spinbox is set to values with a coefficient of 0.1, i.e. in the range from 0 to 10.
Can you tell me if it is reasonable to use templates in this situation? and if so, how to describe it?
Answer the question
In order to leave comments, you need to log in
One can use std::variant ( https://en.cppreference.com/w/cpp/utility/variant ), if new pluses are not available then tagged union ( https://en.wikipedia.org/wiki/Tagged_union there there is an example on the pluses).
You can also use templates. If new pluses are available, then look towards if constexpr ( https://en.cppreference.com/w/cpp/language/if there are examples closer to the bottom). If new pluses are not available, then enable_if ( https://en.cppreference.com/w/cpp/types/enable_if ) + std::is_same ( https://en.cppreference.com/w/cpp/types/is_same ) or std::is_integer/std::is_floating_point ( https://en.cppreference.com/w/cpp/types/is_integer /https://en.cppreference.com/w/cpp/types/is_floatin... ).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question