另一个奇怪的编译器错误:调用一个给出未定义引用的模板化函数
Another strange compiler error: calling a templated function which gives undefined referenes
到目前为止,一切顺利。但是,出现了一些问题。
首先,当我调用以下内容时:
const bool bppExists = CheckMapForExistingEntry< std::string, int >( mConfigValues, "bpp" );
我得到以下信息:
error: undefined reference to `bool CheckMapForExistingEntry<std::string, int>(std::map<std::string, int, std::less<std::string>, std::allocator<std::pair<std::string const, int> > > const&, std::string const&)'
还有其他三个发生这种情况的例子。该函数如下所示:
声明
template < class Key, class Value >
bool CheckMapForExistingEntry( const std::map< Key, Value >& map, const std::string& key );
定义
template < class Key, class Value >
bool CheckMapForExistingEntry( const std::map< Key, Value >& map, const std::string& key )
{
typename std::map< Key, Value >::iterator it = map.lower_bound( key );
bool keyExists = ( it != map.end && !( map.key_comp() ( key, it->first ) ) );
if ( keyExists )
{
return true;
}
return false;
}
那么,这里发生了什么?我包含包含函数声明的头文件,但它仍然不起作用。据此,我应该省略模板参数的值,只传递key_type
,但是这也拒绝工作。
例如:
CheckMapForExistingEntry< std::string >( someMap, "somekey" ); //error
您不能轻松地在标头和源文件之间拆分声明和模板的定义;因此模板通常在标头中定义。例如,请参阅"为什么模板只能在头文件中实现?
此外,在这种情况下,您无需显式提供任何类型参数:
CheckMapForExistingEntry(m, "x");
Key
和Value
的类型可以从map
类型自动推导出来。
请注意,您的函数可以显著缩短,例如:
template < class Key, class Value >
bool contains(const std::map<Key, Value>& map, const std::string& key) {
return map.find(key) != map.end();
}
此外,还可以通用化 key
参数的类型,使函数更易于重用。
相关文章:
- MacOS 上的 Xcode 11 项目不在一个函数中使用 sin 和 cos:未定义的符号"___sincosf_stret"
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 在VSCode中编译C++给了我一个未定义的参考
- 我可以定义一个 constexpr 匿名/未命名变量吗?
- 访问从联合与另一个成员集复制的联合中的一个成员是否未定义或未指定?
- 为什么T是未定义的?我正在尝试实现一个用于双链表的节点类,它不喜欢我使用友元运算符后的T
- 在另一个文件中初始化的 extern 数组中未定义的引用
- 我对C++程序有一个未定义的参考,不知道如何处理它
- 我正在尝试在我的类中创建一个静态成员,但编译器警告我它是未定义的
- 对 Class::Class() 和函数在一个文件中的未定义引用? c++
- 为什么这是一个未定义的行为?
- 从其后声明的另一个成员数据初始化成员数据是否为未定义行为
- 对另一个静态库中静态库方法的未定义引用
- 在链接链接静态(GSOAP)库的共享库时,为什么会得到一个未定义的符号
- 如何将一个或多个(未定义的数字)参数传递给函数
- 对于我的 ComplexNumber 中的某些方法,我得到了一个奇怪的未定义错误引用.cpp,不过我对模板很陌生
- 为什么当我尝试编译时,我的 c++ 代码不断返回对我的一个构造函数的"未定义的引用"?
- 错误访问另一个插件中的类(错误:未定义的引用)
- 给自己一个std::shared_ptr<std::thread>。已定义或未定义的行为
- 对函数的未定义引用,该功能是另一个类的成员