代码之家  ›  专栏  ›  技术社区  ›  jcarpenter2

需要静态模板方法的模板概念不满足约束条件

  •  0
  • jcarpenter2  · 技术社区  · 8 年前

    我正在努力实现 Functor 以及其他各种使用C++概念的范畴论概念,但我遇到了编译错误:

    http://coliru.stacked-crooked.com/a/e8b6eb387229bddf

    这是我的全部代码(我知道 fmap<int, int> 无法验证 fmap 对于任何两种类型,我计划将其更改为 fmap<int, std::string> 或者是为了达到更强的测试,或者可能改变 函子 除了 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 函数声明,然后代码编译并运行。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Casey    8 年前

    问题正是错误消息所说的: Functor_Impl<F>::template fmap<int, int>(x) 不是有效的表达式。 Functor_Impl<std::vector>::fmap 有两个参数,而不是一个。