gpt4 book ai didi

c++ - 模板类友元运算符成员函数

转载 作者:可可西里 更新时间:2023-11-01 17:44:47 26 4
gpt4 key购买 nike

我试图让一个模板化类中的友元函数进行编译,但我不明白错误消息和警告。我已经对这个问题进行了演示。我得到的错误是:

prog.cpp:8:57: error: non-class, non-variable partial specialization C operator+(const B& lhs, const C& rhs);

prog.cpp:15:59: warning: friend declaration 'C operator+(const B&, const C&)' declares a non-template function [-Wnon-template-friend] friend C operator+(const B& lhs, const C& rhs);

prog.cpp:15:59: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)

#include <iostream>
using namespace std;

template<typename A, typename B>
class C;

template<typename A, typename B>
C<A, B> operator+<A, B>(const B& lhs, const C<A, B>& rhs);

template<typename A, typename B>
struct C
{
A val_;
C operator+(const C& other) const;
friend C<A, B> operator+(const B& lhs, const C<A, B>& rhs);
};

template<typename A, typename B>
C<A, B> C<A, B>::operator+(const C<A, B>& other) const
{
C<A, B> c;
c.val_ = this->val_ + other.val_;
return c;
}

template<typename A, typename B>
C<A, B> operator+(const B& lhs, const C<A, B>& rhs)
{
C<A, B> c;
c.val_ = lhs + rhs.val_;
return c;
}

int main()
{
C<string, char> c0,c1;
c0.val_ = " C0 ";
c1.val_ = " C1 ";
cout << "Stuct:" << (c0 + c1).val_ << '\n';
cout << "Friend:" << ('~' + c1).val_ << endl;
return 0;
}

最佳答案

最简单的是在类中内联代码:

template <typename A, typename B>
struct C
{
A val_;
C operator+(const C& other) const
{
C c;
c.val_ = this->val_ + other.val_;
return c;
}

friend C operator+ (const B& lhs, const C& rhs)
{
C c;
c.val_ = lhs + rhs.val_;
return c;
}
};

Demo

类中没有内联的代码,需要特别注意声明的前向声明顺序,奇怪语法<> :

template <typename A, typename B> struct C;

template <typename A, typename B>
C<A, B> operator+ (const B& lhs, const C<A, B>& rhs);

template <typename A, typename B>
struct C
{
A val_;

friend C<A, B> operator+<> (const B& lhs, const C<A, B>& rhs);

C operator+(const C& other) const;
};


template <typename A, typename B>
C<A, B> operator+ (const B& lhs, const C<A, B>& rhs)
{
C<A, B> c;
c.val_ = lhs + rhs.val_;
return c;
}

template <typename A, typename B>
C<A, B> C::operator+(const C<A, B>& other) const
{
C<A, B> c;
c.val_ = this->val_ + other.val_;
return c;
}

Demo

关于c++ - 模板类友元运算符成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36988730/

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