c++ - 需要静态模板方法的模板模板概念不满足约束
问题描述
我正在尝试Functor
使用 C++ 概念来实现和其他各种类别理论概念,但出现编译错误:
http://coliru.stacked-crooked.com/a/e8b6eb387229bddf
这是我的完整代码(我知道 requiresfmap<int, int>
不会验证fmap
任何两种类型,我计划将其更改为fmap<int, std::string>
或其他东西以实现稍强的测试 - 或者相反,可能会更改Functor
概念以便它除了F
, 两个类型T
和U
并验证 的存在fmap<T, U>
,但这就是在我弄清楚如何修复我得到的错误之后):
#include <functional>
#include <iostream>
#include <vector>
// empty Functor_Impl struct - specialize for each functor
template<template<class> class F> struct Functor_Impl {};
// std::vector Functor implementation
template<>
struct Functor_Impl<std::vector> {
template<class T, class U>
static std::vector<U> fmap(std::vector<T> x, std::function<U(T)> f) {
std::vector<U> out;
out.reserve(x.size());
for (int i = 0; i < x.size(); i++) {
out.push_back(f(x[i]));
}
return out;
}
};
// Functor concept requires Functor_Impl<F> to have fmap
template<template<class> class F>
concept bool Functor = requires(F<int> x) {
{Functor_Impl<F>::template fmap<int, int>(x)} -> F<int>;
};
// Test function using constraint.
template<template<class> class F, class T>
requires Functor<F>
F<T> mult_by_2(F<T> a) {
return Functor_Impl<F>::template fmap<T, T>(a, [](T x) {
return x * 2;
});
}
int main() {
std::vector<int> x = {1, 2, 3};
std::vector<int> x2 = mult_by_2(x);
for (int i = 0; i < x2.size(); i++) {
std::cout << x2[i] << std::endl;
}
}
和编译错误:
lol@foldingmachinebox:~/p/website-editor$ g++ foo.cpp -std=c++17 -fconcepts -o foo
foo.cpp: In function ‘int main()’:
foo.cpp:39:38: error: cannot call function ‘F<T> mult_by_2(F<T>) [with F = std::vector; T = int]’
std::vector<int> x2 = mult_by_2(x);
^
foo.cpp:31:6: note: constraints not satisfied
F<T> mult_by_2(F<T> a) {
^~~~~~~~~
foo.cpp:24:14: note: within ‘template<template<class> class F> concept const bool Functor<F> [with F = std::vector]’
concept bool Functor = requires(F<int> x) {
^~~~~~~
foo.cpp:24:14: note: with ‘std::vector<int> x’
foo.cpp:24:14: note: the required expression ‘Functor_Impl<F>::fmap<int, int>(x)’ would be ill-formed
我猜我的概念本身的语法是错误的 - 它将变量视为函数,反之亦然,因为我对concept
语法不是很熟悉,另外一些示例代码cppreference.com
无法编译在 GCC 的实现下(例如concept EqualityComparable
不编译,必须改为concept bool EqualityComparable
)。
如果我requires Functor<F>
从mult_by_2
函数声明中删除,那么代码将编译并运行。
解决方案
问题正是错误消息所说的:Functor_Impl<F>::template fmap<int, int>(x)
不是有效的表达式。Functor_Impl<std::vector>::fmap
有两个参数,不是一个。
推荐阅读
- asp.net - 中继器中的 ASP.NET 单选按钮显示旧值
- java - 对java运算符优先级计算结果感到困惑
- performance - 循环数百行时如何提高速度?
- python - 数组之间的内存共享问题
- rxjs - 在 RxJS 中包装运算符,以便将其应用于物化流
- interpolation - 函数“approx3d”背后的数学
- arrays - 在 Swift 模型中解码数组(可解码)
- slurm - Snakemake 如何使用 --cluster-status 和 sacct 解析 slurm jobid
- authentication - rtsp 身份验证:摘要
- python - 如何针对 python 中的 Azure 存储 blob 对用户进行身份验证?