I have an "Extra" template class defined in "extra.h" with the "doSomething" function, and I defined two specializations of "doSomething". Two different functions create objects of type Extra, each with a different type parameter, and each calls a different specialization. Two client functions "client1" and "client2" are defined in two files "client1.cpp" and "client2.cpp" respectively. In the third file, "main" calls "client1" and then "client2". Now "client1.cpp" and "client2.cpp" are both #include "extra.h". I get a linker error that "doSomething" has (2) several definitions. Naturally, if I put the definitions of "client1" and "client2" in the same source file,I do not have this problem. Is there a way to keep the location of different files for "client1" and "client2"? Below is my code. Thank!
#ifndef EXTRA_H
#define EXTRA_H
template <typename T>
class Extra
{
public:
Extra(T);
~Extra();
T doSomething(T);
private:
Extra() {}
T m_value;
};
template <typename T> Extra<T>::Extra(T input) : m_value{input} {}
template <typename T> Extra<T>::~Extra() {}
template <> int Extra<int>::doSomething(int input)
{
return input * m_value;
}
template <> double Extra<double>::doSomething(double input)
{
return input + m_value;
}
template <typename T> T Extra<T>::doSomething(T input)
{
return input;
}
#endif
#include "extra.h"
#include <iostream>
void client1()
{
std::cout << "In client1." << std::endl;
Extra<int> extra(2);
int res = extra.doSomething(3);
std::cout << "Value: " << res << std::endl;
}
#include "extra.h"
#include <iostream>
void client2()
{
std::cout << "In client2." << std::endl;
Extra<double> extra(2.0);
double res = extra.doSomething(2.0);
std::cout << "Value: " << res << std::endl;
}
#include <iostream>
void client1();
void client2();
int main()
{
std::cout << "In main." << std::endl;
client1();
client2();
return 0;
}
, , :
$ g++ -std=c++11 -o client client1.cpp client2.cpp main.cpp
duplicate symbol __ZN5ExtraIiE11doSomethingEi in:
/var/folders/mf/jdvfkpms609206zpz8x5237r0000gn/T/client1-6fa7ed.o
/var/folders/mf/jdvfkpms609206zpz8x5237r0000gn/T/client2-387444.o
duplicate symbol __ZN5ExtraIdE11doSomethingEd in:
/var/folders/mf/jdvfkpms609206zpz8x5237r0000gn/T/client1-6fa7ed.o
/var/folders/mf/jdvfkpms609206zpz8x5237r0000gn/T/client2-387444.o
ld: 2 duplicate symbols for architecture x86_64