【问题标题】:c++: Identifier T is undefinedc++: Identifier T is undefined
【发布时间】: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&lt;typename T&gt; only affects the single function after it? Yet you're using T in the last overload as well, without writing template&lt;typename T&gt; 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


【解决方案1】:

Your template is only applied 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(const std::vector<T> &vec) {
    ...
}

That being said...

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

  • the 3rd overload can simply return vec.size() instead of calling the 1st overload at all:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多