Home > OS >  How do I cast a typename variable parameter as a string
How do I cast a typename variable parameter as a string

Time:03-31

The problem: I am trying to create a function capable of finding the largest number if the array is an integer, double, float, etc. If the array given is a string it returns the string in the string with the most letters. However, I don't know how to cast list [0] and list[i] as strings.

#include <isostream>
#include <algorithm>
using namespace std;
    unsigned int strlength(string word) {
            char *ch = &word[0];
            unsigned int count = 0;
            while (*ch != '\0') {
                count  ;
                ch  ;
            }
    
            return *count;
        }
       
    
        template<typename U>
        U maxNumber(U list[], int size) {
            unsigned int i;
            if (typeid(list) == typeid(string*)) {
                unsigned int i;
                for (i = 0; i < size; i  ) {
                    if (strlength(list[0]) < strlength(list[i])) {
    
                        list[0] = list[i];
                    }
                    else {
                        list[0] = list[0];
                    }
                }
    
                return list[0];
            }
            else {
                for (i = 0; i < size; i  ) {
                    if (list[0] < list[i]) {
                        list[0] = list[i];
                    }
                    else {
                        continue;
                    }
                }
                return list[0];
    
            }
        }

CodePudding user response:

if (typeid(list) == typeid(string*)) is the wrong tool.

You need compile time branch,

  • either with if constexpr

    template<typename U>
    U maxNumber(U list[], int size) {
        if constexpr (std::is_same_v<U, std::string>) {
            auto less_by_size = [](const auto& lhs, const auto rhs){
                return lhs.size() < rhs.size(); };
            return *std::max_element(list, list   size, less_by_size);
        } else {
            return *std::max_element(list, list   size);
        }
    }
    
  • or via overload/tag dispatching

    std::string maxNumber(std::string list[], int size) {
        auto less_by_size = [](const auto& lhs, const auto rhs){
            return lhs.size() < rhs.size(); };
        return *std::max_element(list, list   size, less_by_size);
    }
    template<typename U>
    U maxNumber(U list[], int size) {
        return *std::max_element(list, list   size);
    }
    
  • Related