静态嵌套bool会帮助我禁用对某些类型的调用吗?或者有更干净的方法吗

Would a static nested bool help me disable a call for certain types or is there a cleaner way?

本文关键字:调用 或者 方法 类型 帮助 bool 嵌套 静态      更新时间:2023-10-16

我有一个模板类,比如:

template<class T>
class someClient
{
void someCallbackA() {foo_->onA();}
void someCallbackB() {foo_->onB();}
private:
T* foo_;
};

我可以用支持CCD_ 1和CCD_。我碰巧遇到这样一种情况,我使用的几种不同类型的T中有两种需要由someClient控制的特定行为,所以我需要在这两种类型中添加一些函数doBar()(称它们为Edge1Edge2)。然后,我希望someClient代码的一部分调用foo_->doBar(),但当onA0的类型没有它时,不要中断。有没有一种方法可以使用boost::enable_if来拥有一个someClient::doBar(),它只会对这两种类型调用foo_->doBar(),但不存在,或者如果类型不是Edge1Edge2,则扩展为无?

我当时的想法是:

template <class T, enable_if<mpl_or<is_same<T,Edge1>, is_same<T,Edge2> > >
someClient<T>::doBar() {foo_->doBar();}

如果不调用没有意义的成员函数,就根本不需要使用任何特殊技巧。模板成员函数只有在需要时才专门化(除非添加了明确的专门化)。因此以下代码运行良好:

template <typename T> struct Foo
{
    void do_foo() { p->foo(); }
    void do_bar() { p->bar(); }
    T * p;
};
struct A { void foo() {} };
int main()
{
    A a;
    Foo<A> x = { &a };
    x.do_foo();
}

Foo<A>::do_bar不会编译这一事实并不是问题,因为成员函数从未被实例化。p->bar不是编译器错误,因为p有一个依赖类型,因此该行只在第二个查找阶段解析(这从未发生)。

我认为这符合您的要求。我使用C++11<type_traits>而不是boost的:

struct Edge {
    void doBar() { std::cout << "did Bar."; }
};
template<typename T>
class someClient
{
public:
    template<typename U = T>
    typename
    std::enable_if<std::is_same<U, Edge>::value, void>::type
    doBar() { foo_->doBar(); }
    template<typename U = T>
    void doBar( typename std::enable_if<!std::is_same<U, Edge>::value, void>::type* = 0 )
    { /* do nothing */ }

private:
    T* foo_;
};
int main()
{
    someClient<int> i;
    someClient<Edge> e;
    i.doBar();
    e.doBar();  // outputs "did Bar."
}

onB0需要作为模板本身才能工作,这里的解释是:std::enable_if有条件地编译成员函数

相关文章: