加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 模板类中的Typedef不起作用

发布时间:2020-12-16 10:19:35 所属栏目:百科 来源:网络整理
导读:参见英文答案 Where and why do I have to put the “template” and “typename” keywords?????????????????????????????????????6个 这可能是一个愚蠢的问题,但我盯着这段代码一段时间,却想不出什么是错的.在编译时: #include string#include maptemplat
参见英文答案 > Where and why do I have to put the “template” and “typename” keywords?????????????????????????????????????6个
这可能是一个愚蠢的问题,但我盯着这段代码一段时间,却想不出什么是错的.在编译时:

#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,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-name-lookup-types.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读