'C++ friend template function: Function definition not found
While trying to wrap my head around C++ templates I have run into a compiler warning I do not understand. In below vec.h
Visual Studio 2019 will put a green squiggle under operator<<<T>
in class vec
with the warning "Function definition for operator<<<T>
not found.
The code otherwise compiles and runs fine. In particular I do not understand how this case differs from operator+
which does not generate a warning.
#pragma once
#include <iostream>
template<typename T>
class vec;
template<typename T>
vec<T> operator+(const vec<T>& a, const vec<T>& b);
template<typename T>
std::ostream& operator<<(std::ostream& os, const vec<T>& v);
template<typename T>
class vec {
public:
vec(T xx = 0, T yy = 0) : x(xx), y(yy) {}
friend vec<T> operator+<T>(const vec<T>& a, const vec<T>& b);
friend std::ostream& operator<<<T>(std::ostream& os, const vec<T>& v);
private:
T x, y;
};
In vec.cpp
I put the function templates for the friend functions and some explicit instantiations.
#include <iostream>
#include "vec.h"
template<typename T>
vec<T> operator+(const vec<T>& a, const vec<T>& b) {
return vec<T>(a.x + b.x, a.y + b.y);
}
template vec<int> operator+(const vec<int>& a, const vec<int>& b);
template vec<float> operator+(const vec<float>& a, const vec<float>& b);
template<typename T>
std::ostream& operator<<(std::ostream& os, const vec<T>& v) {
return os << "<" << v.x << "," << v.y << ">";
}
template std::ostream& operator<<(std::ostream& os, const vec<int>& v);
template std::ostream& operator<<(std::ostream& os, const vec<float>& v);
Solution 1:[1]
This is just an incorrect warning by Visual Studio IntelliSense. The code is well-formed and is compiled successfully.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | cigien |