我有一个模板类(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);
答案 0 :(得分:1)
在你成为朋友之前首先声明函数函数。
// 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
声明应该没问题。
答案 1 :(得分:1)
问题是由于您没有声明成员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