0

I'm learning c++ for the first time. I want to develop a template to calculate length of a const char*, char[] without having to redefine the same function.

I have tried,

template <class N> N length(N str){
    int pos = 0;
    while (str[pos] != '\0'){pos++;}
    return pos; 
}

But I got an error, since I should return N class. Can I fix this?

3
  • 1
    FWIW, both a pointer and an array argument will work with a const char* parameter. No need for a template there. There's also std::string and std::string_view, which have functions to get their length (among many other useful features). Commented Oct 12, 2020 at 4:02
  • 2
    You can just make your function return an int, it doesn't have to return an N just because it's templated over class N. Commented Oct 12, 2020 at 4:03
  • 1
    If str is a const char*, what should the return type be? If str is a std::string instance, what should the return type be? Do you see a pattern? Commented Oct 12, 2020 at 4:10

2 Answers 2

2

I want to develop a template to calculate length of a const char*, char[] without having to redefine the same function.

char[] will implicitly convert to a const char*, so you don't need a template. It is sufficient to write a function that accepts a const char*. Also, such function exists in the standard library so there is no need to write the function except for exercise purposes.

But I got an error, since I should return N class.

Your return statement has the type int, which makes sense for returning a length. But you've declared that the function returns N object instead. This does not make sense for a function that is supposed to return a length. Solution: Declare the function to return an integer type. std::size_t is conventionally used for array / string lengths.

Sign up to request clarification or add additional context in comments.

Comments

1

There are functions to do that but if you want to use templates, here is a function.

Note that u return N and u ask how to solve this problem while u should return size_t.

#include <iostream>

template <size_t N>
constexpr size_t length(const char (&arr) [N]){
    return N-1;
}
int main(){
    char arr [3] = "me";
    std::cout << length(arr) << " " << length("me");
}

Demo

Note that this template won't work if \0 is not at the end of the characters array and won't work with char* as @errorikta has mentioned.

It's just for practice. to know the size of those strings use std::strlen from <cstring> and you can see a possible implementation in the attached link.

1 Comment

What if the array is char arr [42] = "me";? You might also want to clarify that this template does not work with a pointer to char.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.