我可以在成员函数上使用boost :: enable_if吗?

我正在编写模板类,我想允许另一种方法仅存在于某种模板类型。目前,该方法适用于所有模板类型,但会导致所有其他类型的编译错误。 使这更复杂的是它是一个重载的operator()。不知道我想要做什么实际上是可能的。 这就是我现在拥有的:
template<typename T, typename BASE>
class MyClass  : public BASE
{
public:

    typename T& operator() (const Utility1<BASE>& foo);
    typename T const& operator() (const Utility2<BASE>& foo) const;
};
我希望
T&
版本始终可用,但只有
Utility2<BASE>
有效时才能使用
T const&
版本。现在,两种方法都存在,但如果
Utility2<BASE>
无效,则尝试使用const版本会产生奇怪的编译错误。我宁愿有一个明智的错误,甚至是“没有这样的成员函数”错误。 这可能吗? 编辑:阅读了升级文档,这是我提出的,它似乎工作:
template<typename T, typename BASE>
class MyClass  : public BASE
{
public:

    typename T& operator() (const Utility1<BASE>& foo);

    template<typename U>
    typename boost::enable_if<boost::is_same<Utility2<BASE>, U>, T>::type const &
    operator() (const U& foo) const;
};
因此,除非有人试图将它与Utility2一起使用,否则它不存在,并且如果它对该BASE类型有效,则它们只能创建一个Utility2。但是当它对BASE类型无效时,MyClass不会浪费时间创建存取方法。     
已邀请:
是的,这是可能的,但不能直接使用类模板参数。
boost::enable_if
只能与方法本身的模板参数一起使用。所以,使用一点typedef:
template<typename T, typename BASE>
class MyClass  : public BASE
{
public:
  typedef Utility2<BASE> util;

  typename T& operator() (const Utility1<BASE>& foo);

  template<typename U>
  typename boost::enable_if<boost::is_same<util, U>, T>::type const &
  operator() (const U& foo) const;
};
这是有效的,因为Utility2只能从某种BASE类型创建。因此,如果BASE类型是其他类型,则operator()的const版本将不存在。 所以,这是一件非常小的事情。它并没有让我受益匪浅。但这很干净。     

要回复问题请先登录注册