【问题标题】:How to tell if a "->" operator eventually returns a type?如何判断“->”运算符最终是否返回类型?
【发布时间】:2016-05-11 01:00:12
【问题描述】:

我意识到operator-> 返回的任何东西都会在这样的函数调用中调用它自己的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"
  }
};

有什么办法吗?

【问题讨论】:

  • 是否必须“按原样”使用某个类,或者您可以为该类添加特定方法或成员,以实现此模板限制?
  • 您希望它在链调用、第一次调用或链的末尾返回A(所以A*)?
  • 您是否尝试过在A*declltype(var.operator-&gt;()) 之间使用std::is_same 的静态断言(如果相关,则在丢弃const 之后)?
  • @Jarod42 我希望链的末端是A*
  • @TonyD 这不起作用,因为declltype(var.operator-&gt;()) 可能是介于两者之间的类型(例如A* 可能是var.operator-&gt;().operator-&gt;();

标签: c++ templates operator-keyword


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 2013-08-19
    • 2012-06-07
    • 2010-10-06
    • 2013-11-21
    • 2015-01-29
    相关资源
    最近更新 更多