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

Tim*_*Tim 7 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;
};
Run Code Online (Sandbox Code Playgroud)

我希望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;
};
Run Code Online (Sandbox Code Playgroud)

因此,除非有人试图将它与Utility2一起使用,否则它不存在,并且如果它对该BASE类型有效,则它们只能创建一个Utility2.但是当它对BASE类型无效时,MyClass不会浪费时间创建访问器方法.

Tim*_*Tim 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;
};
Run Code Online (Sandbox Code Playgroud)

这是可行的,因为 Utility2 只能从特定的 BASE 类型创建。因此,如果 BASE 类型是其他类型,则 operator() 的 const 版本将不存在。

所以,这是一件非常小的事情。对我来说收获不大。但做起来很整洁。