简体   繁体   English

未定义参考模板Const和函数

[英]Undefined Reference to a template Const & function

Function header:(Templated Outer Class Map has inner class Iterator) 函数头:(模板化的外部类映射具有内部类迭代器)

Iterator insert(const std::pair<const T1, T2>&);

Function Implementation: 功能实施:

template<typename T1, typename T2>
typename Map<T1,T2>::Iterator insert(const std::pair<const T1, T2> &p)

Code to call insert function: 调用插入函数的代码:

std::pair<int,char>p = std::make_pair(5, 'z');
mymap3.insert(p);

Compilation with g++ -g -std=c++11, Error: 使用g ++ -g -std = c ++ 11进行编译,错误:

 In function `main':
testmap.cpp:535: undefined reference to 
Map<int, char>::insert(std::pair<int const, char> const&)'
collect2: error: ld returned 1 exit status

Why does the compiler assumer the definition of insert is now (pair const &) instead of my definition of (const pair &) is there a difference? 为什么编译器现在定义insert(对const&)而不是我对(const pair&)的定义是否存在差异? Am I calling this inappropriately? 我不恰当地称呼这个吗? I'm very befuddled. 我很迷惑。 Yes, this is for class, we are re-implementing map. 是的,这是为了上课,我们正在重新实施地图。 So the function definition was a given, I just need to find out how to call it and make it work. 所以函数定义是给定的,我只需要找出如何调用它并使其工作。

This function: 这个功能:

template<typename T1, typename T2>
typename Map<T1,T2>::Iterator insert(const std::pair<const T1, T2> &p)

when declared outside the class definition of Map , is not a member function - it defines a global insert . 当在Map的类定义之外声明时,它不是成员函数 - 它定义了一个全局insert

This is a member of Map<T1, T2> declared at namespace scope (ie, outside the class definition): 这是在命名空间范围内声明的Map<T1, T2>的成员(即,在类定义之外):

template<typename T1, typename T2>
typename Map<T1,T2>::Iterator Map<T1,T2>::insert(const std::pair<const T1, T2> &p)

Note that the member function name has been qualified by the class name, which in this case is Map<T1, T2> . 请注意,成员函数名称已由类名限定,在本例中为Map<T1, T2>

On a related note, using a trailing return type would let you get rid of some of the nastiness in the return type, since names in a trailing return type are resolved in the scope of the class: 在相关的说明中,使用尾随返回类型可以让你摆脱返回类型中的一些肮脏,因为尾随返回类型中的名称在类的范围内被解析:

template<typename T1, typename T2>
auto Map<T1, T2>::insert(const std::pair<const T1, T2> &p) -> Iterator;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM