【问题标题】:using declarations for template function of template base class使用模板基类的模板函数的声明
【发布时间】:2017-03-27 18:55:28
【问题描述】:

我想用一个基类的模板函数,像这样:

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>(); }
};

然而这并不能编译。

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

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

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>(); }
};

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

【问题讨论】:

    标签: c++ templates inheritance using-statement


    【解决方案1】:

    编译器不知道f&lt;int&gt;() 中的f 是模板,因此会出现错误消息。

    您可以在没有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>(); }
    };
    

    【讨论】:

    • 而且没有办法明确告诉它是模板吗?在进行试验时,编译器收到了一些关于将“模板”放入 using 语句的消息,但我不知道广告在哪里无法重现该提示。
    • 我没有找到办法。尝试在所有可以添加模板的地方添加模板,但根本问题似乎是您不能模板化 using 声明,并且没有函数别名。
    • 好的,谢谢。我记得我是怎么得到这个打击的。命中是error: use 'template' keyword to treat 'f' as a dependent template name using A_type::f&lt;int&gt;;,我是通过using A_type::f&lt;int&gt;;而不是using A_type::f;得到的
    猜你喜欢
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    相关资源
    最近更新 更多