使用模板基类的模板函数声明

lo *_*cre 5 c++ inheritance templates using-statement

我想使用基类的模板函数,如下所示:

struct A {
  template <class T> static auto f() { \*code*\ }
};

template <class A_type> struct B : public A_type {

  using A_type::f;

  void g() { auto n = f<int>(); }
};
Run Code Online (Sandbox Code Playgroud)

但是,这不会编译。

error: expected '(' for function-style cast or type
      construction
  void g() { auto n = f<int>(); }
                        ~~~^
error: expected expression
  void g() { auto n = f<int>(); }
Run Code Online (Sandbox Code Playgroud)

但是直接引用基类而不是模板确实有效:

struct A {
  template <class T> static auto f() { \*code*\ }
};

template <class A_type> struct B : public A_type {

  using A::f;

  void g() { auto n = f<int>(); }
};
Run Code Online (Sandbox Code Playgroud)

为什么第一个版本不能编译而第二个版本可以。我需要做些什么不同的事情才能让它发挥作用?

eml*_*lai 3

编译器不知道finf<int>()是模板,因此会出现错误消息。

你可以不用像这样来做到这using一点:

struct A {
    template <class T> static auto f() { /*code*/ }
};

template <class A_type> struct B : public A_type {
    void g() { auto n = A_type::template f<int>(); }
};
Run Code Online (Sandbox Code Playgroud)