当我在不同的目标文件中使用专用模板时,链接时出现"多重定义"错误.我找到的唯一解决方案涉及使用"内联"功能,但它似乎只是一些解决方法.如何在不使用"inline"关键字的情况下解决这个问题?如果那不可能,为什么?
这是示例代码:
paulo@aeris:~/teste/cpp/redef$ cat hello.h
#ifndef TEMPLATE_H
#define TEMPLATE_H
#include <iostream>
template <class T>
class Hello
{
public:
void print_hello(T var);
};
template <class T>
void Hello<T>::print_hello(T var)
{
std::cout << "Hello generic function " << var << "\n";
}
template <> //inline
void Hello<int>::print_hello(int var)
{
std::cout << "Hello specialized function " << var << "\n";
}
#endif
Run Code Online (Sandbox Code Playgroud)
paulo@aeris:~/teste/cpp/redef$ cat other.h
#include <iostream>
void other_func();
Run Code Online (Sandbox Code Playgroud)
paulo@aeris:~/teste/cpp/redef$ cat other.c
#include "other.h"
#include "hello.h"
void other_func()
{
Hello<char> hc;
Hello<int> hi; …
Run Code Online (Sandbox Code Playgroud)