【问题标题】:How to call a derived templated function in CRTP? [duplicate]如何在 CRTP 中调用派生的模板化函数? [复制]
【发布时间】:2017-04-11 11:17:23
【问题描述】:

我的尝试是:

template<typename Derived>
struct Base
{
    void A()
    {
        ((Derived *)this)->B<42>();
    }
};

struct Derived : Base<Derived>
{
    template<int> void B() { }
};

(http://coliru.stacked-crooked.com/a/cb24dd811b562466)

结果

main.cpp: In member function 'void Base<Derived>::A()':
main.cpp:6:34: error: expected primary-expression before ')' token
         ((Derived *)this)->B<42>();
                                  ^
main.cpp: In instantiation of 'void Base<Derived>::A() [with Derived = Derived]':
main.cpp:17:17:   required from here
main.cpp:6:30: error: invalid operands of types '<unresolved overloaded function type>' and 'int' to binary 'operator<'
      ((Derived *)this)->B<42>();
      ~~~~~~~~~~~~~~~~~~~~^~~

【问题讨论】:

  • 编译器错误? VS 2017 工作正常
  • @Raxvan MSVC 不执行两阶段查找,这也是它在那里工作正常的部分原因。不是编译器错误。

标签: c++ templates inheritance crtp


【解决方案1】:

您需要keyword template 来调用依赖类型上的模板函数:

((Derived *)this)->template B<42>();
//                 ~~~~~~~~

在模板定义中,template 可用于声明依赖名称是模板。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 2021-06-10
    • 2014-09-23
    相关资源
    最近更新 更多