c++ - 模板运算符 ->

标签 c++ templates

<分区>

有没有办法方便地调用模板运算符->? 在变体这样的类中有这种可能性会很酷

例如:(那只是一个例子)

struct base_t
{
   template<class T>
   T* operator->()
   {
      return reinterpret_cast<T*>(this);
   }
};

int main(int argc, char* argv[])
{
   base_t x;
   x.operator-><std::pair<int,int>>()->first; //works, but inconvenient
   x<std::pair<int,int>>->first; // does not work
   x-><std::pair<int,int>>first; //does not work

   return 0;
}

我需要证据 =)

最佳答案

不,这不是真的,这怎么也不是真的

struct base_t
{
   template<class T>
   T operator () ()
   {
      return T();
   }
};

int main()
{
   base_t x;
   x.operator ()<int>(); // works
   x.()<int>(); // not works
}

An expression x->m is interpreted as (x.operator->())->m for a class object x of type T if T::operator->() exists and if the operator is selected as the best match function by the overload resolution mechanism

postfix-expression -> templateopt id-expression

postfix-expression -> pseudo-destructor-name

因此,语法 x-><T>完全不正确。

关于c++ - 模板运算符 ->,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15833489/

相关文章:

c++ - 我不明白为什么第二个版本的代码片段可以编译。 AFAIK 它不应该,因为 §10.3/2

c++ - 使用 boost Spirit x3 解析为集合

c++ - 允许运行时和编译时多态性的灵活方式?

c++ - MFC/C++ 相当于 VB 的 AppActivate

c++ - C多线程编程中的文件输入和输出(windows)

c++ - 在 C++ 应用程序中使用 HyperLedger Fabric

c++ - 返回值的静态模板函数特化

c++ - 推断类型是否来自模板类的方法

c++ - 将 'void' 作为函数参数传递

c++ - 无法将对象上的指针添加到集合