我有一个包含两个相似成员函数的类模板:
template<class T>
class MyTemplate {
// other stuff, then
static T* member( T& ); //line 100
static const T* member( const T& ); //line 101
};
我这样实例化:
MyTemplate<int* const>
和 Visual C++ 9 提示:
mytemplate.h(101) : error C2535: 'int* MyTemplate<T>::member(T &)' :
member function already defined or declared
with
[
T=int *const
]
mytemplate.h(100) : see declaration of 'MyTemplate::member'
with
[
T=int *const
]
somefile.cpp(line) : see reference to class template instantiation
'MyTemplate<T>' being compiled
with
[
T=int *const
]
我当然需要 member()
的两个版本 - 一个用于 const 引用,一个用于非常量引用。我猜这个问题与顶级 const 限定符有关,但无法推断出如何解决它。
如何解决这个问题,以便我仍然有两个版本的 member()
并且模板可以编译?
最佳答案
fefe给出的解释是正确的。 Foo const&
和 Foo const const&
将简单地评估为相同的类型,因此您的函数重载不起作用。如果您的模板参数是 const,我建议专门化。
版本 A:
template<class T>
class MyTemplate {
static T* member( T& );
static const T* member( const T& );
};
template<class T>
class MyTemplate<T const> {
static const T* member( const T& );
};
版本 B:
template<class T>
class MyTemplate_mutableImpl {
static T* member( T& );
};
template<class T>
class MyTemplate_constImpl {
static const T* member( const T& );
};
template<class T>
class MyTemplate : public MyTemplate_mutableImpl<T>, public MyTemplate_constImpl<T> {
};
template<class T>
class MyTemplate<T const> : public MyTemplate_constImpl<T const> {
};
关于c++ - 如何用顶级 const 解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8485622/