kar*_*uch 3 c++ templates typedef
这可能是一个愚蠢的问题,但我盯着这段代码一段时间,却想不出什么是错的.在编译时:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我明白了:
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’
Run Code Online (Sandbox Code Playgroud)
(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;
}
Run Code Online (Sandbox Code Playgroud)
一切正常.为什么它不工作和/或如何使其工作?
在此先感谢您的帮助
尝试typename在my_string_map<T>::type争论之前.
有关详细信息,请参阅:https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-types.