我正在写一个模板类,我想允许一个额外的方法只存在于特定的模板类型中。目前该方法适用于所有模板类型,但会导致所有其他类型的编译错误。
复杂的是它是一个重载的 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/