模板化类中友元运算符的多个定义
Multiple definitions of friend operator in templated class
我有以下代码片段:
template < typename T1, typename T2 >
class Test
{
public:
Test() = default;
private:
template < typename T1_, typename T2_ >
friend Test< T1_, T2_ > operator*( const Test< T1_, T2_ >& lhs, const Test< T1_, T2_ >& rhs )
{
return Test< T1_, T2_ >();
}
};
int main( int argc, char* argv[] )
{
{
Test< int, int > t1;
Test< int, int > t2;
Test< int, int > t3 = t1 * t2;
}
{
Test< double, double > t1;
Test< double, double > t2;
Test< double, double > t3 = t1 * t2;
}
}
使用 clang 3.9,代码编译良好,使用 gcc 6.3.1,我收到以下错误:
redefinition of ‘template<class T1_, class T2_> Test<T1_, T2_> operator*(const Test<T1_, T2_>&, const Test<T1_, T2_>&)’
friend Test< T1_, T2_ > operator*( const Test< T1_, T2_ >& lhs, const Test< T1_, T2_ >& rhs )
哪个编译器是正确的?
如果是我怀疑的 gcc,我如何在类中正确声明模板化运算符*。类内定义对我来说对于参数依赖查找是必要的。
GCC 是正确的,因为Test
的每个实例化都定义了模板operator*
,这些模板是相同的,因为它们的签名不依赖于T1
或T2
。 operator*
在这里不需要是模板,只是Test
的特定实例化的重载:
template < typename T1, typename T2 >
class Test
{
friend Test operator*(const Test& lhs, const Test& rhs)
{
return Test();
}
};
int main( int argc, char* argv[] )
{
{
Test< int, int > t1;
Test< int, int > t2;
Test< int, int > t3 = t1 * t2;
}
{
Test< double, double > t1;
Test< double, double > t2;
Test< double, double > t3 = t1 * t2;
}
}
这将定义两个非模板重载的operator*
,一个用于Test
的每个实例化。
相关文章:
- 在 C++ 的自定义运算符中删除与删除[](不同于常见的删除与删除[]问题)
- 自定义运算符重载C++,无开销
- 如何为缺少预定义运算符而不扩展命名空间"std"的标准类型定义运算符>> (istream &, ...)?
- 如何使用C++将MXNET自定义运算符构建到单独的库/包中?
- 模板类的用户定义运算符上的 C++ 隐式转换
- 什么是编程语言支持定义您自己的自定义运算符?
- 如何在Qt中为矩阵类定义[ ][ ]运算符?
- 在 c++ 迭代器中,我应该同时定义运算符== 和运算符!=吗?
- 在 rxcpp 中创建自定义运算符
- 错误 C2676;在C++的二叉搜索树类中定义 ++ 运算符时遇到问题
- std::map :使用自定义运算符时更新密钥
- 最初定义运算符C++在哪里
- 如何在Tensorflow Lite中添加自定义运算符
- 如何在 rxcpp 自定义运算符中正确推断泛型
- 在模板化类之外定义运算符重载
- 为类定义之外的模板类定义运算符[]()(数组订阅)
- 是否可以在类定义之外定义运算符[]()(数组订阅)
- C++ 重新定义运算符<() 和运算符!=()
- 如何将上下文信息传递给自定义运算符<<适用于 std::iostream
- 无法在C++中定义++运算符,这里有什么问题?