Check int or list <int>

Can someone please let me know how best to do 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 to check if & ag is the only object or list of objects. In addition, with this template interface.

It doesn't matter if the answer matches the template specification in any way to the class interface. The only thing I do not want to specify the type of the object or the type of the list.

Ex. ag = int or ag = list

NE

+6
source share
4 answers

You can eliminate some character 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 */) {} } 

Look here
This trait clearly just extends numeric types, not a container. The return type will take some work. There are ideas for determining the type of container in the answers here and here.

+2
source

Hmm, maybe all you need is a simple overload?

 template<typename ARGUMENT> void get_result(ARGUMENT& ag); template<typename ARGUMENT> void get_result(std::list<ARGUMENT>& ag); 

Edit:

Reading your comments, I feel that you are trying to overestimate your function and give it a lot of responsibilities.

I think you will be better off with the first overload. Whenever you need to apply a function to an entire range, use for_each .

+7
source

Do you mean this?

 template<typename ARGUMENT> void get_result(ARGUMENT &ag) { std::cout<<typeid(ARGUMENT).name(); //Check the value /*This returns a name of the type in question. It may satisfy your criteria.*/ } //Header :#include <typeinfo> 

So,

 int x=12; list <int> l; get_result<list<int>>(l); // Outputs: St4listIiSaIiEE get_result<int>(x); //Outputs: i 
+1
source

SFINAE:

 template<typename T> T get_result(T arg, typename T::value_type* = 0) { // Container. } template<typename T> T get_result(T arg, ...) { // Not a container. Vararg overloads rank lower in overload resolution. } 
+1
source

Source: https://habr.com/ru/post/950506/


All Articles