Can anybody please let me know the best way to accomplish this.
Say, I have a template function like
template<typename ARGUMENT>
void get_result(ARGUMENT &ag)
{
// arg can be a single object of a particular object or list of objects of that particular class.
//rest
}
Is there a way that I can check if the &ag is a single object or list of objects. Also, with the given template interface.
It does not matter if the answer is by template specification in some way by a class interface. Only thing is I do not want to specify the object type or list type.
Ex. ag = int or ag = list
CB
How to check if all list elements are numbers? In a list comprehension, for each element in the list, check if it's an integer using the isinstance() function.
The 'all' operator is used to check if every element is a digit or not. This is done using the 'isdigit' method. The result of this operation is assigned to a variable.
-> List[int] means that the function should return a list of integers.
Hmm, maybe all you need is simple overloading?
template<typename ARGUMENT>
void get_result(ARGUMENT& ag);
template<typename ARGUMENT>
void get_result(std::list<ARGUMENT>& ag);
Edit:
Reading your comments, I have a feeling you're trying to overdesign your function and give it to many responsibilities.
I think you'd be best off with the first overload only. Whenever you need to apply the function to a whole range, use for_each
.
You could disambiguate with some type traits:
#include <type_traits>
template<typename T>
T get_result(T arg)
{
return detail::get_result(arg, typename std::is_arithmetic<T>::type() );
}
namespace detail {
template<typename T>
T get_result(T arg, std::false_type /* dummy */) { }
template<typename T>
T get_result(T arg, std::true_type /* dummy */) {}
}
See here
This trait clearly just pulls out the numeric types, rather than a container. The return type will take some work. There are ideas for detecting a container type in the answers here and here
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