c++ - 对模板类成员的 undefined reference

标签 c++

在尝试使用样本输入运行 Pairwise 类后,我得到了一个 undefined reference 。我的 Pairwise 类是在头文件中创建的,我创建了一个主要函数来将键和值作为字符串传递,以便按照我的意愿对它们进行格式化。

我的预期输出:

key:value

我的头文件:

#pragma once

#include<iostream>
using std::ostream; using std::cout; using std::endl;
#include<string>
using std::string;
#include<sstream>
using std::ostringstream;

template<typename K, typename V> 
   struct Pairwise { 
   K first; 
   V second; 
   Pairwise() = default; 
   Pairwise(K,V); 
   friend ostream& operator<<(ostream &out, const Pairwise &p){
        out << p.first << ":" << p.second;
        return out;
    }
   };

我的主要功能:

#include "file.h"

#include<iostream>
using std::cout; using std::endl;
#include<sstream>
using std::ostringstream;
#include<string>
using std::string;

int main()
{
    Pairwise<string,string> p("key", "value");

    ostringstream oss;
    oss<<p;
    string example = oss.str();
    cout << example << endl;
}

我得到的错误:

/tmp/ccfv4iaY.o: In function `main':
main_program.cpp:(.text+0x8b): undefined reference to `Pairwise<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::Pairwise(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: error: ld returned 1 exit status

最佳答案

您的模板包含 Pairwise(K,V); 的声明,但它从未在任何地方定义/实现。

您需要在同一个(或另一个)头文件中添加定义。要验证,将 ; 替换为 {},链接器错误应该消失:Pairwise(K,V) {}(它赢了' 工作,但它会编译和链接正常)。

关于c++ - 对模板类成员的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53464403/

相关文章:

c++ - 如何在 ImGui 列中右对齐文本?

c++ - 你能在 C++ 中动态创建 for 循环吗?

c++ - 使用字符串来描述函数参数

c++ - DebugActiveProcess 是否也跟踪子进程?

c++ - Boost::Mpi 是否支持并行IO

c++ - 在 qsort 之后识别项目/类指针

c++ - uBLAS 慢速矩阵-稀疏 vector 乘法

c++ - 开关盒中的 char 和 int 有什么区别?

c++ - 从 ‘void* (*)()’ 到 ‘void* (*)(void*)’ [-fpermissive] 的无效转换

c++ - eof 和 fail 的区别