I received such a task - to make a template function that can accept an int float string and return half of the numbers and strings.
There are no ideas at all .. Here is a sketch that compiles but gives an error when calling ..

 template <typename Type> Type max(Type a) { if (typeid(a).name()[0]=='A'){ // тип строка if (strlen(a)>1) { //больше одной буквы a[strlen(a)/2]='\0';} // режем пополам return a; //возвр строку }else{ return a/2;//вовр число } } 

for example, what should be in the end Challenges:

  int a = max(10); // 5 float b = max(5.8); //2.9 string c =max("Hashcode") //Hash 

Help, please, or give an idea or an example of how to do it)

    2 answers 2

    It's simple: http://ideone.com/VJ4LH1

    This is called an “explicit template specialization”.

     template<typename T> T half(T arg); template<> int half<int>(int arg) { return arg/2; } template<> double half<double>(double arg) { return arg/2; } template<> string half<string>(string arg) { return arg.substr(0, arg.length()/2); } 

    For more advanced cases, read about SFINAE .

    • As far as I understand, with the help of SFINAE it is necessary to make the following template (suitable for the condition of the problem): 1. check if the operator / defined for the type, if yes - use it. In this case, it becomes unnecessary to determine the specialization of the pattern for integer and real numbers. 2. if not, check whether the type is a container (string, vector, list, etc.). If yes, return the first half of the container. 3. in other cases, return the error. - gecube
    • one
      @gecube: with SFINAE something like this: ideone.com/DuBaF5 Or more simply, with boost::enable_if / boost::is_arithmetic . - VladD

    Whoever asked you this at all understands what templates are and why are they?

    In general, template functions are made when the data type changes and the algorithm is the same, and in the case of

    1. int,float ... you need to divide the variable by 2 and return the result
    2. string find the middle, create a new line, copy half there (by the way, which half exactly?) and return the result

    3. and what to do in the case of objects?

    4. What to do in the case of collections?

    As you can see, the algorithm is different everywhere ...




    You can of course be perverted and make an explicit template predetermination for a certain type (I forgot the exact name of such templates)

    or even greater perversion with the type definition inside the template

    • one
      > you can of course be perverted and make an explicit template predetermination for a certain type (forgot the exact name of such templates) Template specialization ??? - gecube
    • Yeah, she's the one! - ProkletyiPirat