代码之家  ›  专栏  ›  技术社区  ›  DarthRubik

如何判断“->”运算符是否最终返回类型?

  •  1
  • DarthRubik  · 技术社区  · 9 年前

    我意识到 operator-> 将称其为自己的 运算符-> 在这样的函数调用中:

    someVarWithOverloadedOperator->someFunc();
    

    还有打电话的过程 -> 函数将继续,直到其中一个是指针,然后 someFunc 从该指针调用。

    我的问题是:有没有办法强制模板参数具有 -> 运算符最终返回某个类:

    template<typename ThisClassOperatorMustReturn_TypeA_>
    class MyClass{
      void foo() {
        ThisClassOperatorMustReturn_TypeA_ var;  
        var->someClassAFunc();  //I need this `->` operator to return type "A"
      }
    };
    

    有什么办法吗?

    1 回复  |  直到 9 年前
        1
  •  2
  •   Jarod42    9 年前

    您可以为此创建一个特征:

    template <typename T>
    using arrow_type = decltype(std::declval<T>().operator ->());
    
    template <typename T, typename ArrowType = arrow_type<T>>
    struct arrow_last_type
    {
        using type = typename arrow_last_type<ArrowType>::type;
    };
    
    template <typename T, typename P>
    struct arrow_last_type<T, P*>
    {
         using type = P*;  
    };
    

    然后

    static_assert(std::is_same<A*, arrow_last_type<ClassToTest>::type>::value, "unexpected");
    

    Demo