【问题标题】:Can a template class alias itself without specifying its template parameters twice?模板类是否可以在不指定其模板参数两次的情况下为其自身命名?
【发布时间】:2021-08-26 00:07:04
【问题描述】:

我正在尝试定义一个具有许多参数的新类模板。为了编写一些方法(例如重载运算符),我想给模板类类型起别名。现在我正在这样做:

template <class T, int a, int b, int c, int d, int e, int f>
class ExampleClass {

  using ExampleClassType = ExampleClass<T, a, b, c, d, e, f>;

  // for example,
  ExampleClassType operator+(const ExampleClassType& rhs) {
    // ...
  }

};

这种方法似乎是多余的,因为我将模板参数列表写了两次。有没有更好的办法?我天真地尝试过

using ExampleClassType = decltype(*this);

但这不起作用,我认为因为this 在编译时是未知的。

抱歉,如果这是一个重复的问题,我尝试搜索但没有找到任何具体的内容。

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    您实际上可以为此目的使用ExampleClass。它被称为injected class name,您可以在类定义中使用它,它将隐含地成为完全实例化的类。

    例子:

    #include <iostream>
    
    template<class T, int a>
    struct ExampleClass
    {
        ExampleClass operator+(const ExampleClass& t_rhs) const { std::cout << a << '\n'; return *this; }
    };
    
    
    int main(int argc, char** argv){
        ExampleClass<int, 7> myClass;
        auto foo = myClass + myClass;
    }
    

    on godbolt

    这将输出7,因为在我的operator+ 中,ExampleClass 实际上被用作注入的类名,意思是ExampleClass&lt;int, 7&gt;

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 1970-01-01
      • 2018-02-28
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多