需要静态模板方法的模板概念不满足约束 我试图用C++概念实现函子< /代码>和其他各种范畴理论概念,但是我得到编译错误:
这是我的全部代码(我知道要求需要静态模板方法的模板概念不满足约束 我试图用C++概念实现函子< /代码>和其他各种范畴理论概念,但是我得到编译错误:,c++,templates,c++-concepts,template-templates,C++,Templates,C++ Concepts,Template Templates,这是我的全部代码(我知道要求fmap并不能验证任何两种类型的fmap,我计划将其更改为fmap或实现稍微更强的测试——或者,可能改变函子的概念,以便在F之外,还需要两种类型T和U和ve。)验证是否存在fmap,但这都是在我弄清楚如何修复我得到的错误之后): #包括 #包括 #包括 //空函子\u Impl struct-为每个函子专门化 模板结构函子_Impl{}; //向量函子实现 模板 结构函子{ 模板 静态std::vector fmap(std::vector x,std::functi
fmap
并不能验证任何两种类型的fmap
,我计划将其更改为fmap
或实现稍微更强的测试——或者,可能改变函子
的概念,以便在F
之外,还需要两种类型T
和U
和ve。)验证是否存在fmap
,但这都是在我弄清楚如何修复我得到的错误之后):
#包括
#包括
#包括
//空函子\u Impl struct-为每个函子专门化
模板结构函子_Impl{};
//向量函子实现
模板
结构函子{
模板
静态std::vector fmap(std::vector x,std::function f){
std::向量输出;
out.reserve(x.size());
对于(int i=0;iF;
};
//使用约束测试函数。
模板
需要函子
F乘2(F a){
返回函子_Impl::模板fmap(a,[](tx){
返回x*2;
});
}
int main(){
向量x={1,2,3};
std::向量x2=乘以2(x);
对于(int i=0;i std::cout问题正是错误消息所说的:Functor\u Impl::template fmap(x)
不是有效的表达式。Functor\u Impl::fmap
有两个参数,而不是一个。lordy,我可以删除这个问题:/
#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