【问题标题】:Disambiguating argument-less function calls in variadic class hierarchies消除可变参数类层次结构中的无参数函数调用的歧义
【发布时间】:2010-08-17 19:07:34
【问题描述】:

我试图为从可变参数层次结构(下面的 ObjGetter)派生的类(下面的 MyGizmo)的用户提供一种简单、整洁的方式来明确调用不带参数的成员函数(下面的 check())。我可以使用带参数的函数(如下面的 tune())来实现这一点,但我还没有找到一种方法让它适用于不带参数的函数。

struct Base { };
struct ObjA : public Base { };
struct ObjB : public Base { };
struct ObjC : public Base { };

template <class ... Obj> struct ObjGetter;

template <class Obj, class ... Tail>
struct ObjGetter<Obj, Tail ...> : public ObjGetter<Tail ...>
{
  using ObjGetter<Tail ...>::tune;  // resolve ambiguous lookups for tune()

  void tune(Obj * obj) { } // no problem with this one, disambiguated by obj type

  Obj * check() const { return 0; } // problem with this one, no arg to disambiguate
};

template <> struct ObjGetter<> { // to terminate the recursion
  void tune(void);  // needed by the using statement above but should not be used, hence different syntax
};

struct MyGizmo : public ObjGetter<ObjA, ObjC> // variadic
{
  void testit() {
    ObjA * a = 0; ObjB *b = 0; ObjC *c = 0;

    a = ObjGetter<ObjA, ObjC>::check(); // too ugly!
    c = ObjGetter<ObjC>::check(); // too ugly!

    tune(a); // no problem
    //tune(b); // correct compile-time error: no matching function for call to ‘MyGizmo::tune(ObjB*&)’
    tune(c); // no problem

    // I would like a simple syntax like this:
    //a = check<ObjA>(); // should call ObjGetter<ObjA, ObjC>::check()
    //b = check<ObjB>(); // should give a compile-time error
    //c = check<ObjC>(); // should call ObjGetter<ObjC>::check()
  }
};

我尝试了以下方法,但并不完全满意:

首先,我可以使用在层次结构中携带的辅助的、简单模板化的类,以减少只有一个模板参数的丑陋调用;产生类似的东西:

a = ObjGetterHelper<ObjA>::check(); // still ugly! MyGizmo user should not have to know about ObjGetterCore
c = ObjGetterHelper<ObjC>::check(); // too ugly!

我可以使用 Type2Type 助手并给 check() 一个参数,这很好用,看起来像这样:

a = check(Type2Type<ObjA>()); // pretty ugly too
c = check(Type2Type<ObjC>()); // pretty ugly too

我可以使用宏,但我不想去那里......

#define CHECK(X) check(Type2Type<X>())

我认为模板别名将提供一个解决方案,但我使用的 g++ 尚不支持它们。这期间还有什么事情吗?非常感谢!

【问题讨论】:

  • check 是做什么的?我理解这个问题,但是当我首先不知道如何处理check 时,很难给出正确的答案。 (都是return 0;吗?价值从何而来?)
  • check() 实际上轮询黑板上是否有某个对象已被张贴到它上面并且可用。在完整的实现中,它返回一个 shared_ptr 到发布的对象(如果存在)或一个空的 shared_ptr。

标签: c++ templates c++11 variadic


【解决方案1】:

如果类型与可变参数列表的头部不匹配,您需要一个具有某种结构的成员函数模板check&lt;Type&gt; 来委派继承链。

这是 SFINAE 的经典问题。

  template< class Obj2 >
  typename std::enable_if< std::is_same< Obj, Obj2 >::value, Obj * >::type
  check() const { return 0; } // perform work

  template< class Obj2 >
  typename std::enable_if< ! std::is_same< Obj, Obj2 >::value, Obj2 * >::type
  check() const { return base::template check< Obj2 >(); } // delegate

与我的其他答案相同。我将把那个作为巴洛克愚蠢的例子。

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多