如何使用c++中的类模板声明新的运算符
How to declare new operator using the class template in c++
我有一个模板类(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
相关文章:
- 在哪里声明结构运算符重载
- 让某个类的 '=' 运算符在声明时运行构造函数
- 为什么我在声明对象数组时不能使用 -> 运算符?
- 在一个指令中声明更多指针的运算符优先级
- 类模板中文本运算符的友元声明
- 新运算符分配的大小大于声明的大小.为什么
- 统一初始化是隐式发生的,即使 int 强制转换运算符是使用 explicit 关键字声明的.原因是什么?
- 为什么我不能定义一元运算符,然后在 MSVC 的模板类中声明具有相同名称的友元二进制运算符?
- 为什么重载运算符>在参数声明 const 时不起作用?
- Ho 在标头中声明是结构中的重载运算符?
- 是否可以将引用类型别名与指针运算符一起使用来声明对指针的引用?
- C++ 03 类模板 这是转换构造函数还是转换运算符?以及如何声明解决此问题的方法
- 具有继承的未声明标识符(运算符 ostream)
- 我可以在工会内声明运算符吗?
- 不能在函数中声明运算符.叮当错误或规范
- 使用宏声明运算符
- 在C++中声明运算符+函数
- 如何声明运算符重载<以在需要时在类变量之间动态切换?
- 未声明运算符++后缀
- 如何为内部类声明运算符<<