Home > Software design >  C Templates: expected constructor, destructor, or type conversion
C Templates: expected constructor, destructor, or type conversion

Time:01-01

I am trying to build a library with a templated class having a constraint on the value of the integer passed:

library.h

template<int N>
requires (N == 1)
class example {

public:

    example();

};

library.cpp:

#include "library.h"

main.ccp:

#include "library.h"

int main() {
    return 0;
}

However, when trying to compile main.cpp, the compiler throws me the following error:

error: expected constructor, destructor, or type conversion before '(' token

I noticed that if I do not include library.h in main.ccp, the build compiles successfully, but I have nothing else in my main.ccp and I am not really sure what is happening.

I appreciate any help solving the issue as I cannot continue working on this if I cannot compile.

CodePudding user response:

As Charles Savoie already wrote in his comment, the requires keyword is new since C version 20.

Older compilers do not know that keyword; for such compilers requires is just an identifier like example or helloWorld.

You might try to replace requires by helloWorld to check if your compiler supports requires:

template<int N>
helloWorld (N == 1)
class example {
  public:
    example();
};

Of course, this will cause some error message in any case.

However, if you get exactly the same error message that you get now, it is very probable that your compiler does not support the requires keyword.

You can try to get a newer compiler, of course.

But in this case, it is probable that your library can only be used by the latest compilers so you will also require a very recent compiler when you write a program that uses your library.

If you want your library to be compatible with less recent compilers, you must avoid the requires keyword.

  • Related