C++ 什么时候用`.template` 和 `::template`-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

C++ 什么时候用.template::template

简单来说就是你有一个未知类型T**这个T本身就是模板**
假设这个T是一个类这个类里包含了一些模板函数或者模板结构体
你需要使用T. 或者 T:: 去调用他们并且要显示指定模板参数
这个时候就需要用到.template::template

如果上面文字描述没懂没关系看示例就懂了

编译环境: gcc/g++ 13.2 -std=c++17

struct A {
  void Foo() { std::cout << __PRETTY_FUNCTION__ << std::endl; }

  template <typename T>
  void Foo() {
    std::cout << __PRETTY_FUNCTION__ << std::endl;
  }

  template <typename T>
  static void Goo() {
    std::cout << __PRETTY_FUNCTION__ << std::endl;
  }

  template <typename T>
  struct B {
    using type = T;
    void Foo() { std::cout << __PRETTY_FUNCTION__ << std::endl; }
    template <typename U>
    void Foo() {
      std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
  };

  struct C {
    void Foo() { std::cout << __PRETTY_FUNCTION__ << std::endl; }
  };
};

template <typename T>
struct Test {
  void Fun(T t) {
    t.Foo();
    t.template Foo<int>();

    t.template Goo<int>();
    T::template Goo<int>();

    typename T::template B<int>::type a;
    typename T::template B<int>().Foo();
    typename T::template B<int>().template Foo<int>();

    typename T::C().Foo();
  }
};

int main() {
  A a;
  Test<A>().Fun(a);
}

编译输出内容

void A::Foo()
void A::Foo() [with T = int]
static void A::Goo() [with T = int]
static void A::Goo() [with T = int]
void A::B<T>::Foo() [with T = int]
void A::B<T>::Foo() [with U = int; T = int]
void A::C::Foo()
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: c++