I've taken the project I'm working on and shortened it to three brief files that replicate what's happening. I'm working with the Code::Blocks IDE using g++ under the 2011 standard.
The files are main.cpp
, thing.cpp
and thing.h
. The header (.h
) has declarations and the source (.cpp
) has implementations. The thing
files define a class Thing
with a template parameter T
. All Thing
does is hold an object of type T
(it basically does nothing).
main.cpp
:
#include <iostream>
#include "thing.h"
int main(){
Thing<int> a(9);
Thing<double> b(3.2);
auto c = a + b;
c.display();
return 0;
}
thing.h
:
#ifndef THING_H
#define THING_H
template<typename T>
class Thing{
private:
T content;
public:
Thing(const T& content);
~Thing(){};
T get_content() const;
void display();
};
template<typename S, typename T>
auto operator+(const Thing<S>& s, const Thing<T>& t);
#endif // THING_H
thing.cpp
:
#include "thing.h"
#include <iostream>
template<typename T>
Thing<T>::Thing(const T& content)
:content(content){}
template<typename T>
void Thing<T>::display(){
std::cout << content << '\n';
}
template<typename T>
T Thing<T>::get_content() const {
return content;
}
template<typename S, typename T>
auto operator+(const Thing<S>& s, const Thing<T>& t){
S s_content = s.get_content();
T t_content = t.get_content();
Thing<typename std::common_type<S, T>::type> sum = s_content + t_content;
return sum;
}
Here's the strange behavior: the code will compile or not depending on the line #include "thing.h"
. Using thing.h
here will not compile, causing an error:
error: use of 'auto operator+(const Thing<S>&, const Thing<T>&) [with S = int; T = double]' before deduction of 'auto'
error: invalid use of 'auto'
Changing this line to #include "thing.cpp"
allows the code to compile without problems and functions as intended (it outputs 12.2
to the console).
My question is: What is the compiler doing differently in the two cases? How can I change the code to eliminate this error when includ
ing the header?
Thanks in advance.
& s, const Thing& t);` to work with. It needs the code. – WhozCraig May 25 '17 at 19:43