我在下面有一个简单的代码片段,它使用以下命令编译:
g++-9 -std=c++2a -fconcepts
这是在尝试定义一个需要函数存在的概念。我希望输出结果是"yes“,但事实并非如此。知道为什么吗?谢谢。
#include <iostream>
template <typename T>
concept bool HasFunc1 =
requires(T) {
{ T::func1() } -> int;
};
struct Test
{
int func1()
{
return 5;
}
};
int main()
{
if constexpr (HasFunc1<Test>)
std::cout << "yes\n";
}发布于 2019-10-15 20:23:06
您正在测试是否存在静态成员函数。你想要的是
template <typename T>
concept bool HasFunc1 =
requires(T t) {
{ t.func1() } -> int;
};发布于 2019-10-15 20:23:51
尝试自己调用它:
Test::func1();
prog.cc: In function 'int main()':
prog.cc:19:14: error: cannot call member function 'int Test::func1()' without object
19 | Test::func1();
| ^哦,对了。func1应该是static成员函数,或者应该在概念中的实例上调用它:
template <typename T>
concept bool HasFunc1 =
requires(T t) {
{ t.func1() } -> int;
};发布于 2020-06-07 11:27:15
可以在编译时运行概念检查。(操作的检查仅在运行时计算。)
首先,准备一个检查器函数(从技术上讲,这是一个模板化的变量):
template <HasFunc1 h>
constexpr bool HasFunc1_satisfied = true;那就找个地方检查一下。
// The class to be tested
struct Test
{
int func1()
{
return 5;
}
};
// Do the test at the compile time
static_assert(HasFunc1_satisfied< Test >);https://stackoverflow.com/questions/58394556
复制相似问题