I have following template code:
class ClassName{};
template <class T>
class TemplatePtr
{
public:
void operator=(T* p)
{
}
};
class TemplatePtr_ClassName: public TemplateePtr<ClassName>
{
public:
~TempaltePtr_ClassName();
};
void Test()
{
TemplatePtr_ClassName data;
data = new ClassName;
}
but compile fails with error message (VS2008):
error C2679: binary '=' : no operator found which takes a right-hand operand of type >>'ClassName *' (or there is no acceptable conversion)
Why it won't work as I have defined an operator in the templat开发者_运维技巧e base class?
It gets inherited. However, the compiler-generated assignment operator for TempaltePtr_ClassName
hides the inherited operator. You can make it visible by adding
using TempaltePtr<ClassName>::operator=;
to your derived class.
operator = is always hidden by the derived class implementation unless explicit using declaration is provided. This is true for both class templates and ordinary classes.
BTW, your declaration of operator= is very nonstandard. It is usually declared so for a class 'A'.
A& operator=(A const &);
Here is something that may be what you are looking for (and compiles)
template <class T>
class TemplatePtr
{
public:
TemplatePtr& operator=(TemplatePtr const &)
{return *this;}
};
template<class T>
class TemplatePtr_ClassName: public TemplatePtr<T>
{
public:
~TemplatePtr_ClassName(){};
TemplatePtr_ClassName& operator=(TemplatePtr_ClassName const &that){
TemplatePtr<T>::operator=(that); // invoke base class assignment operator
return *this;
}
};
int main()
{
TemplatePtr_ClassName<int> data;
data = *new TemplatePtr_ClassName<int>;
// delete stuff
}
精彩评论