如何使用c++中的类模板声明新的运算符

How to declare new operator using the class template in c++

本文关键字:声明 运算符 何使用 c++      更新时间:2023-10-16

我有一个模板类(Word):

template<int C>
class Word {
...
}

我想添加一个操作员:

friend Word<C> operator&(Word<C>& word1, Word<C>& word2);   // & operator between all bits

所以现在我有了:

template<int C>
class Word {
   ...
   friend Word<C> operator&(Word<C>& word1, Word<C>& word2);    // & operator between all bits
}
template<int C>
Word<C> operator&(Word<C>& word1, Word<C>& word2) {
    Word<C> ans = new Word<C>;
    for (int i = 0; i < C; i++) {
        ans[i] = word1[i] & word2[i];
    }
    return ans;
}

但我得到了这个标记:

Multiple markers at this line
    - (if this is not what you intended, make sure the function template has already been declared and add <> after the function name 
     here)
    - friend declaration 'Word<C> operator&(Word<C>&, Word<C>&)' declares a non-template function [-Wnon-template-friend]

使用操作员时出现此错误:

undefined reference to `operator&(Word<8>&, Word<8>&)'

使用代码:

Word<C> tmp1 = (words[i] & mask);

在将函数设为好友之前,请先声明函数。

// Forward declare the class.
template<int C> class Word;
// Declare the function.
template<int C> Word<C> operator&(Word<C>& word1, Word<C>& word2);

然后,类中的friend声明应该是OK。

问题是由于您没有声明成员operator&重载,因此生成的声明没有模板化。如果使用g++进行编译,则会看到与此相关的有用警告消息:

test4.cpp:4:60: warning: friend declaration ‘Word<C> operator&(Word<C>&, Word<C>&)’ declares a non-template function [-Wnon-template-friend]
test4.cpp:4:60: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) 
test4.cpp: In function ‘int main()’:

告诉您类中的友元声明实际上并没有声明模板函数。

要修复此问题,只需模板operator&本身。以下是一个完整的工作示例(注意T != U):

#include <iostream>
using namespace std;
template<int T>
class Word {
  public:
    template<int C>
    friend Word<C> operator&(Word<C>& word1, Word<C>& word2);
};
template<int C>
Word<C> operator&(Word<C>& word1, Word<C>& word2){
  Word<C> ans;
  std::cout << C << std::endl;
  // TODO add your stuff here
  return ans;
}
int main() {
  Word<8> a, b;
  Word<8> c = a & b;
}  

编译并运行:

$ g++ test4.cpp && ./a.out
Inside operator &
8