【发布时间】:2021-11-26 17:20:25
【问题描述】:
在我的一个项目中,我的 C++20 概念之一出现错误“不满足相关约束”。在我看来,我的代码是正确的,所以我一定对语言有误解。
我已重写代码以删除所有明显无关的细节。
这里是包含语句:
#include <array>
#include <memory>
我定义的约束在下面的成员函数Afunc上:
template<typename BLikeType>
class A {
public:
A(std::shared_ptr<C> c_) : c_(std::move(c_)) {}
template<typename... Args>
requires requires (BLikeType t, Args... args) {
{t.Bfunc(c_->Cfunc(args...))};
}
std::array<double, sizeof...(Args)> Afunc(Args... args) {
return c_->Cfunc(args...);
}
private:
std::shared_ptr<C> c_;
};
B 和 C 类的编写方式试图满足上述约束。我使用std::array<double, 2> 只是为了让读者了解A 中的可变参数模板是必要的。
class C {
public:
C() {}
std::array<double, 2> Cfunc(double a, double b) {
return { a, b };
}
};
我还为A中的模板参数BLikeType写了一个类B。如下:
class B {
public:
B(){}
double Bfunc(std::array<double, 2> my_array) {
return my_array[0] + my_array[1];
}
};
然后我尝试在我的主函数中测试这个约束:
int main() {
C c{};
std::shared_ptr<C> c_ptr = std::make_shared<C>(c);
A<B> a(c_ptr);
std::array<double, 2> answer = a.Afunc<double, double>(.1, .2); // Error: the associated constraints are not satisfied
return 0;
}
为什么会出现我的约束不满足的错误?
【问题讨论】:
-
我认为
answer是double而Afunc返回一个数组同样是重写的问题?这就是为什么我们要求minimal reproducible example。 -
另外,特别是在您简化了示例之后,请尝试使用一些不同的编译器 - 像 godbolt.org 这样的网站可以轻松完成。来自其他编译器的错误消息通常很有启发性。
-
@T.C.谢谢,我修复了它,以便 Bfunc 现在返回
std::array<int, 2>。
标签: c++ templates variadic-templates c++20 c++-concepts