-2

I tried creating a template with an argument called T.

But, the problem is that the compiler said that the identifier is undefined when I'm trying to use it.

I tried doing this (len.hpp):

#include <iostream>
#include <vector>

template<typename T>
unsigned int len(T item[]){
    unsigned int res = 0;
    try{
        for (unsigned int i = 0; true; i++){
            item[i];
            res = i;
        }
    }
    catch(...){}
    return res + 1;
}

unsigned int len(std::string str){
    return str.length();
}

unsigned int len(std::vector<T> vec){
    return len(vec.data());
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
AdamGewely
  • 15
  • 1
  • 7
    You understand that `template` only affects the single function after it? Yet you're using `T` in the last overload as well, without writing `template` before it. – HolyBlackCat Dec 01 '22 at 18:55
  • 3
    There are no exceptions for out of bound access, you loop is wrong. – Jarod42 Dec 01 '22 at 19:01
  • @HolyBlackCat Thanks! I originally saw this template tutorial at the Cherno, Without thinking it was only for before the function, – AdamGewely Dec 01 '22 at 19:03
  • @Jarod42, Then how do I get the length? – AdamGewely Dec 01 '22 at 19:04
  • 1
    @AdamGewely one way to get the length of a c-style array would be to make the parameter a reference and let the compiler deduce the correct size, e.g. [godbolt](https://godbolt.org/z/bxrqbhcEE) – Turtlefight Dec 01 '22 at 19:12

1 Answers1

0

Your template is applied only to the 1st overload of len(), but you are trying to use the template's T argument in the 3rd overload as well. So, you need to add another template to the 3rd overload, eg:

#include <iostream>
#include <vector>

template<typename T>
unsigned int len(T item[]) {
    ...
}

// no template is needed here, unless you want this
// function to handle std::(w|u16|u32)string as well...
unsigned int len(std::string str) {
    ...
}

template<typename T>
unsigned int len(std::vector<T> vec) {
    ...
}

That being said...

  • your 1st overload is flawed as it is running an endless loop.

  • the 2nd and 3rd overloads are taking in their input parameters by value, which means they are going to make copies of any data passed to them. To avoid that, they should take in their parameters by (const) reference instead, eg:

    unsigned int len(const std::string &str) {
        ...
    }
    
    template<typename T>
    unsigned int len(const std::vector<T> &vec) {
        ...
    }
    
  • the 3rd overload can simply return vec.size() instead of calling the 1st overload at all, eg:

    template<typename T>
    unsigned int len(const std::vector<T> &vec) {
        return vec.size();
    }
    
  • the standard C++ library already has overloaded std::size() functions that handle C arrays and standard containers. So, your len() functions are basically redundant.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770