Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check int or list<int>

Tags:

c++

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

like image 673
cow boy Avatar asked Jul 29 '13 09:07

cow boy


People also ask

How do I check if a list is int?

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.

How do you check if all elements in a list are numbers?

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.

What is list list int ]] in Python?

-> List[int] means that the function should return a list of integers.


2 Answers

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.

like image 192
jrok Avatar answered Oct 06 '22 00:10

jrok


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

like image 40
doctorlove Avatar answered Oct 06 '22 01:10

doctorlove