Template specialization: template id does not match template declaration

I am trying to use templates but cannot figure out what is wrong with the code below.

solve.h

#include "nlp.h"
#include "Ipopt_solve.h"

enum algo_type {IPOPT =1, SQP};

template<int ALG>
class solve
{
public:
    solve()
    {
    }
};

template<>
class solve<IPOPT>
{
public:
    solve(nlp*);

private:
    Ipopt_solve m_ipopt;

};

      

solve.cpp

template<>
solve<IPOPT>::solve(nlp* problem): m_ipopt(problem)
{
}

      

Ipopt_solve

is a subclass of an abstract class TNLP

. Ipopt_solve

initialized with a reference to the class nlp

.

from main.cpp

nlp problem(&model);
solve<IPOPT> solution(&problem);

      

I am getting error like below.

error: template-id 'solve <>' for 'solve <1> :: solve (nlp *)' does not match template declaration solve :: solve (nlp * problem): m_ipopt (problem)

+3


source to share


2 answers


You have to delete template<>

i.e.

// template <>
solve<IPOPT>::solve(nlp* problem): m_ipopt(problem)
{
}

      



template<>

used to specialize templates (for a template); but you are just defining a non-templated member function (a class template specialization). (Therefore, the compiler complains that the template declaration cannot be found.)

+4


source


This ad is in its original form

template<>
solve<IPOPT>::solve(nlp* problem): m_ipopt(problem)
{
}

      

is formally in itself. However, it doesn't do what you think it does. This declaration declares an explicit specialization for the main template member

template<int ALG>
class solve
{
  ...

      

It has nothing to do with your explicit specialization.

template<>
class solve<IPOPT>
{
  ...

      

The compiler tries to specialize the constructor of the solve<ALG>::solve(nlp* problem)

main template. However, there is no such constructor in the main template. Hence the error message that tells you for sure: the compiler does not understand which constructor you are trying to allocate, it cannot find the corresponding element in the main template.



For example, you can use this syntax to explicitly specify the default constructor of the main template

template<>
solve<SQP>::solve()
{
  // Specialized code for `solve<SQP>` default constructor
}

      

This will compile just fine as the main template does have such a constructor. (Note that you don't need to explicitly specialize the entire class to do this, you can just explicitly specialize the constructor.)

Your intention was obviously quite different: to provide a constructor definition in a class template specialization

template<>
class solve<IPOPT>
{
  ...

      

The correct syntax for this should not be mentioned template<>

solve<IPOPT>::solve(nlp* problem): m_ipopt(problem)
{
}

      

+4


source







All Articles