mardi 21 août 2018

Specialize function template for set of types

Is it possible to create function template with different behaviour for different sets of types?

Suppose a function with template argument, that should accept ANY type, without compile fail

template<typename T>
void foo(T arg){
    std::cout << arg;
} 

Surely, this won't compile for types having no operator<<. I want to write in std::cout only naive types (i.e. numerical, std:string, const char *), for other types there is meant nothing to print out. So, I tried this (for simplification, i omitted checks for std:string, const char * )

template<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type>
void foo(T arg){
    std::cout << arg;
}

template<typename T, typename = typename std::enable_if<!std::is_arithmetic<T>::value, T>::type>
void foo(T arg){

}

That is, there must be generated overloaded functions with no potential ambiguity. Of course, the code does not compile, since parameters of template are not part of template signature (and thus there are two templates with same signature). So is there any way to play around?

I see the solution in making latter function as main template, and for stated types to create template specializations, but I don't want to bloat my code with identical definitions (and possibly there could be even more types for printing). Is there any way to specialize function template using std::enable_if or smth?

P.S. Boost is unrelevant P.P.S. I've seen this answer Specialize Many Templates for a Set of Types, but i don't get how to adopt it, that is all types possible could be passed to function, not only few predefined

Aucun commentaire:

Enregistrer un commentaire