C++ 模板:预期的构造函数、析构函数或类型转换

C++ Templates: expected constructor, destructor, or type conversion

我正在尝试构建一个带有模板 class 的库,该库对传递的整数值有限制:

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;
}

但是,当尝试编译 main.cpp 时,编译器抛出以下错误:

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

我注意到,如果我不在 main.ccp 中包含 library.h,构建会成功编译,但我的 main.ccp 中没有其他内容,我不确定是什么正在发生。

感谢任何帮助解决问题的帮助,因为如果我无法编译,我将无法继续处理此问题。

正如 Charles Savoie 在他的评论中所写,requires 关键字是自 C++ 版本 20 以来的新关键字。

旧的编译器不知道那个关键字;对于这样的编译器 requires 只是一个标识符,如 examplehelloWorld.

您可以尝试将 requires 替换为 helloWorld 以检查您的编译器是否支持 requires:

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

当然,这无论如何都会导致一些错误信息。

但是,如果您收到与现在收到的完全相同的错误消息,很可能您的编译器不支持requires关键字。

当然你可以试试更新的编译器。

但在这种情况下,您的库可能只能由最新的编译器使用,因此当您编写使用您的库的程序时,您还需要一个非常新的编译器。

如果您希望您的库与较新的编译器兼容,则必须避免使用 requires 关键字。