【发布时间】:2022-12-02 03:18:08
【问题描述】:
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());
}
【问题讨论】:
-
You understand that
template<typename T>only affects the single function after it? Yet you're usingTin the last overload as well, without writingtemplate<typename T>before it. -
There are no exceptions for out of bound access, you loop is wrong.
-
@HolyBlackCat Thanks! I originally saw this template tutorial at the Cherno, Without thinking it was only for before the function,
-
@Jarod42, Then how do I get the length?
-
@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
标签: c++ templates header-files c++-templates macos-monteray