1

I am writing small matrix library which uses Curiously recurring template pattern and i faced with following problem.

Have to classes Base and Derived. Derived has template parameter which denotes some scalar type. I want to create cast method inside Base which converts Derived-like class to Derived-like with another scalar.

Following code looks quite well but raises compile error in gcc 7.2.0

template<typename Derived>
class Base
{
    public:
    template<typename OtherT>
    auto cast() const 
    {
        return (static_cast<Derived*>(this))->cast<OtherT>();
    }    
};

template<typename T>
class Derived : public Base<Derived<T>>
{
public:
    template<typename OtherT>
    Derived<OtherT> cast() const
    {
        return Derived<OtherT>();
    }
};



int main()
{
    Derived<float>  der;
    return 0;
}

Error message:

a.cpp:14:51: error: expected primary-expression before ‘>’ token
  return (static_cast<Derived*>(this))->cast<OtherT>();
                                                   ^
a.cpp:14:53: error: expected primary-expression before ‘)’ token
  return (static_cast<Derived*>(this))->cast<OtherT>();

But with gcc 6.4.0 everything is ok

Is there a way to fix it?

PS Sorry for my poor English.

Daiver
  • 1,488
  • 3
  • 18
  • 47
  • Try `return (static_cast(this))->template cast();`. – songyuanyao Jun 04 '18 at 08:41
  • @songyuanyao wow, looks like it works, thanks! Can you make an answer with small explanation? – Daiver Jun 04 '18 at 08:43
  • 1
    @Dark_Daiver the compiler was interpreting your `< >` as operator and not as used in template context – Tyker Jun 04 '18 at 08:45
  • 1
    @Dark_Daiver See [Where and why do I have to put the “template” and “typename” keywords?](https://stackoverflow.com/q/610245/3309790). – songyuanyao Jun 04 '18 at 08:48
  • @songyuanyao Thanks for great reading! Can you make an stackoverflow answer to allow me close my question? – Daiver Jun 04 '18 at 10:28
  • @Dark_Daiver If it does solve your problem, that means it's a duplicate. For such case it's supposed to close the question as duplicate. :) – songyuanyao Jun 04 '18 at 10:39

0 Answers0