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

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()
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值