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

标签 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 版本会出现奇怪的编译错误。是无效的。我宁愿有一个合理的错误,甚至是“没有这样的成员函数”错误。

这可能吗?

编辑:在通读了 boost 文档后,这是我想出的,它似乎有效:

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 一起使用,并且他们只能创建一个 Utility2,前提是它对该 BASE 类型有效。但是当它对该 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 版本将不存在。

所以,这是一个非常小的事情。这对我没有太大好处。但这样做很巧妙。

关于c++ - 我可以在成员函数上使用 boost::enable_if 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4880922/

相关文章:

可跨进程共享的 C++ 容器

C++ 将数组传递给函数并读取其成员

C++ 模板和函数解析

asp.net - 如何使用 ASP.NET Web 应用程序模板知道登录何时成功

python - Wagtail/Django block 无法从自定义/嵌套 StructBlock 模板正确呈现内容

c++ - 是否有标准的 C++11 解决方案来转义单引号?

c++ - boost::bimap 中的移位值

c++ - 计算填满国际象棋64个方格总共需要多少米

c++ - 如何在 C++ 中创建强密码字符串?

boost - 无法使用基于 qnx7.0 的 qcc 为 boost_1.68.0 构建 libboost_filesystem.a