Templates: template function not playing well with class's template member function

前端 未结 2 1110
渐次进展
渐次进展 2020-12-02 21:14

This is a minimal test case of some code that I actually have. It fails when it tries to evaluate a.getResult():

test.cpp: In function          


        
相关标签:
2条回答
  • 2020-12-02 21:29

    When you refer to a template that is a member of dependent type, you have to prepend it with a keyword template. This is how the call to getResult inside printStuff should look

    size_t value = a.template getResult<B>();
    

    This is similar to using the keyword typename when referring to nested typenames in a dependent type. For some reason, the bit about typename with nested types is rather well-known, but the similar requirement for template with nested templates is relatively unknown.

    Note that the general syntax structure is a bit different though. The typename is always put in front of the full name of the type, while template is inserted in the middle.

    Again, this is only necessary when you are accessing a template member of a dependent type, which in the above example would be A in printStuff. When you call foo.getResult<> in main the type of foo is not dependent, so there's no need to include the template keyword.

    0 讨论(0)
  • 2020-12-02 21:38

    Your code is ill-formed according to C++ Standard 14.2/4:

    When the name of a member template specialization appears after . or -> in a postfix-expression, or after nested-name-specifier in a qualified-id, and the postfix-expression or qualified-id explicitly depends on a template-parameter (14.6.2), the member template name must be prefixed by the keyword template. Otherwise the name is assumed to name a non-template.

    So, you should write size_t value = a.template getResult<B>();

    0 讨论(0)
提交回复
热议问题