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

标签 c++ templates operator-overloading

我有一个模板类(Word):

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

我想添加一个运算符(operator):

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

最佳答案

先声明函数 function,然后再将其设为友元。

// 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了。

关于c++ - 如何在 C++ 中使用类模板声明新运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33654246/

相关文章:

关于加法运算符重载的 C++ 问题

templates - 如何设置新的joomla模板

c++ - 具有函数类型参数的模板导致编译器错误

C# 中的运算符重载

c++ - 对 vector 的引用在回退后是否会重新定位?如果是,如何?

C++11 风格的 SFINAE 和模板实例化的函数可见性

c++ - 比较c++中对象实例的内存地址

c++ - 从 map 中选择随机元素子集

c++ - 如何为 std::map 使用重载的 std::less

c++ - 将 unsigned char[10] 转换为 QBytearray;