模板类中的Typedef不起作用
Typedef in template class not working
这可能是一个愚蠢的问题,但我盯着这段代码看了一段时间,想不出哪里出了问题。编译时:
#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.
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- (typedef)typename迭代器在c++、qt中不起作用
- Typedef学生不起作用
- A类{..};typedef a a_t;Union u{...; a_t ai;...};不起作用
- 模板 C++ 类中的 typedef 在定义类的外侧时不起作用?
- typedef 有效,'using ='不起作用
- 为什么这个特性类不起作用,来测试一个类是否有某个typedef
- 模板类中的Typedef不起作用