模板类中的Typedef不起作用

Typedef in template class not working

本文关键字:Typedef 不起作用      更新时间:2023-10-16

这可能是一个愚蠢的问题,但我盯着这段代码看了一段时间,想不出哪里出了问题。编译时:

#include <string>
#include <map>
template <typename T>
struct my_string_map {
    typedef std::map<std::string, T> type;
};
template <typename T> bool add_to_string_map(my_string_map<T>::type map,
        std::string str, T x) {
    if (map.find(str) != map.end()) 
        return false;
    map[str] = x;
    return true;
}

我得到:

foo.cpp:8: error: template declaration of ‘bool add_to_string_map’
foo.cpp:8: error: expected ‘)’ before ‘map’
foo.cpp:8: error: expected primary-expression before ‘str’
foo.cpp:8: error: expected primary-expression before ‘x’

(my_string_map类的定义取自本论坛的另一个帖子(

当我专门化我使用的模板类型时,比如在中

bool add_to_string_int_map(my_string_map<int>::type map,
        std::string str, int x) {
    if (map.find(str) != map.end()) 
        return false;
    map[str] = x;
    return true;
}

一切都很好。为什么它不起作用和/或如何使它起作用?

提前感谢您的帮助

尝试将typename放在my_string_map<T>::type参数之前。

有关更多信息,请参阅:https://isocpp.org/wiki/faq/templates#nondependent-名称查找类型。

my_string_map<T>::type依赖名称,因为它依赖于模板参数T。对于从属名称,您需要使用typename:

template <typename T>
bool add_to_string_map(typename my_string_map<T>::type map, std::string str, T x) {
    ...
}

编译器将无法推导出T。这对人类来说是显而易见的,但从编译器的角度来看,这种推导是不可能的。专业化之所以有效,是因为您不再要求编译器推导T.