【问题标题】:C++ friend template function: Function definition not foundC++朋友模板函数:找不到函数定义
【发布时间】:2020-08-21 21:23:06
【问题描述】:

在尝试围绕 C++ 模板进行思考时,我遇到了一个我不理解的编译器警告。在vec.h 下方,Visual Studio 2019 将在class vec 中的operator<<<T> 下方放置一个绿色曲线,并带有警告“未找到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 中,我放置了友元函数和一些显式实例化的函数模板。

#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);

【问题讨论】:

  • 尝试在&lt;&lt;&lt;T&gt; 之间添加一个空格?请注意,这不是编译器警告,而是智能感知警告,并不总是 100% 准确
  • 尝试编译,你得到一个实际的错误吗?
  • 在 之间添加一个空格没有帮助。将 operator> 确实会使曲线消失。所以这可能只是 IntelliSense 的解析问题?
  • 很可能是的,不正确的智能感知警告并不少见。
  • 显示的代码没有问题。 Visual Studio 智能感知警告不正确。

标签: c++ templates visual-studio-2019 friend


【解决方案1】:

这只是 Visual Studio IntelliSense 的错误警告。代码格式正确,编译成功。

【讨论】:

    【解决方案2】:

    或者下面的代码

    // vec.h
    template<typename T>
    class vec;
    
    template<typename T>
    std::ostream& operator<<(std::ostream& os, const vec<T>& v);
    
    template<typename T>
    struct vec {
        friend std::ostream& operator<< <T>(std::ostream& os, const vec<T>& v);
    };
    

    可以写成(不带&lt;&lt;&lt;T&gt;

    // vec.h
    template<typename T>
    struct vec {
        template<typename T>
        friend std::ostream& operator<<(std::ostream& os, const vec<T>& v);
    };
    

    这只是个人喜好问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2014-10-07
      • 2013-07-30
      • 1970-01-01
      相关资源
      最近更新 更多