简体   繁体   中英

Check int or list<int>

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

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

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

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM