如何在 CRTP 中调用派生模板函数?
How to call a derived templated function in CRTP?
我的尝试是:
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>();
~~~~~~~~~~~~~~~~~~~~^~~
您需要 keyword template 来调用依赖类型的模板函数:
((Derived *)this)->template B<42>();
// ~~~~~~~~
Inside a template definition, template
can be used to declare that a dependent name is a template.
我的尝试是:
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>();
~~~~~~~~~~~~~~~~~~~~^~~
您需要 keyword template 来调用依赖类型的模板函数:
((Derived *)this)->template B<42>();
// ~~~~~~~~
Inside a template definition,
template
can be used to declare that a dependent name is a template.