简体   繁体   English

用于类模板专业化的运算符重载

[英]operator overloading for a class template specialization

I got stuck with a confusing problem here and i couldnt find any solution so far: The linker complains about a multiple definition of an overloaded non-member operator==. 我在这里遇到一个令人困惑的问题,到目前为止,我找不到任何解决方案:链接器抱怨重载的非成员运算符==的多重定义。 Imagine the following situation: 想象一下以下情况:

template <class T>
struct MyPtr
{
  T* val;
  ...
}

template <class T> bool operator==(MyPtr<T> const & lhs, MyPtr<T> const & rhs)
{ return *lhs.val == *rhs.val; }
template <class T> bool operator==(MyPtr<T> const & lhs, T* const & rhs)
{ return *lhs.val == *rhs;}

So far so good, everything works like a charme, but as i tried to specialize my class to react to a char* in specific way things get weird: 到目前为止,一切都很好,但是像我尝试让我的班专门对char *做出反应时,事情变得很奇怪:

template <>
struct MyPtr<char>
{
  char* val;
  ...
}

//Now each of these functions result in a multiple definition error of the Linker, 
//and i dont get why:
//bool operator== (MyPtr<char> const& lhs, MyPtr<char> const& rhs)
//{ return strcmp(lhs.val,rhs.val) == 0;}

//template <> bool operator==<char> (MyPtr<char> const& lhs, MyPtr<char> const& rhs)
//{ return strcmp(lhs.val,rhs.val) == 0;}

So what am i doing wrong here? 那我在做什么错呢? The ordering in my code is as it is written here. 我的代码中的顺序与此处编写的相同。 Moving these function definitions above the Class specialization result in the error: 将这些函数定义移到Class专业化之上会导致错误:

Error : specialization of 'MyPtr<char>' after instantiation
Error : redefinition of 'class MyPtr<char>'

Please notice i have to use GCC 4.1.2 . 请注意,我必须使用GCC 4.1.2。 I hope its not a compiler problem here... again... 我希望它不是这里的编译器问题...再次...

A function definition should only appear in a header file if: 在以下情况下,函数定义应仅出现在头文件中:

  • It has been declared with the inline keyword, OR 它已使用inline关键字OR声明。
  • It is defined within a class definition, OR 它是在类定义中定义的,或者
  • It involves at least one template parameter 它涉及至少一个模板参数

(Those are among the cases where the multiple-identical-definitions version of ODR applies.) (这些情况适用于ODR的多定义定义版本。)

So inline is not usually required with template functions. 因此,模板功能通常不需要inline But an explicit specialization doesn't actually have any template parameters, so you should mark it inline if you want it in the header file. 但是显式专门化实际上没有任何模板参数,因此,如果要在头文件中将其inline ,则应将其inline标记。

Shouldn't this 这不应该吗

template <> bool operator==<char> (MyPtr<char> const& lhs, MyPtr<char> const& rhs)
{ return strcmp(lhs.val,rhs.val) == 0;}

be

template <> bool operator==<char> (MyPtr<char> const& lhs, char* const& rhs)
{ return strcmp(lhs.val,rhs) == 0;}

?

Thanks to jogojapan for the corrections 感谢jogojapan的更正

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM