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

时间:2011-02-02 22:57:29

标签: c++ templates 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&版本始终可用,但T const&版本仅在Utility2<BASE>有效时才可用。现在,两种方法都存在,但如果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不会浪费时间创建存取方法。

1 个答案:

答案 0 :(得分:4)

是的,这是可能的,但不能直接使用类模板参数。 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版本将不存在。

所以,这是一件非常小的事情。它并没有让我受益匪浅。但这很干净。