gpt4 book ai didi

c++ - C++ friend 模板函数:找不到函数定义

转载 作者:行者123 更新时间:2023-12-02 10:27:54 28 4
gpt4 key购买 nike

在尝试围绕C++模板时,我遇到了一个编译器警告,我不明白。在vec.h的下面,Visual Studio 2019将在operator<<<T>class vec下的绿色squiggle中显示警告``未找到operator<<<T>的函数定义。
否则,代码将编译并正常运行。特别是我不明白这种情况与operator+有何不同,后者不会生成警告。

#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;
};
vec.cpp中,我为 friend 函数和一些显式实例化放置了函数模板。
#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);

最佳答案

这只是Visual Studio IntelliSense的不正确警告。该代码格式正确并已成功编译。

关于c++ - C++ friend 模板函数:找不到函数定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63530230/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com