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

模板模板参数推导在Clang和MSVC中失败,但在GCC中成功

  •  1
  • Fureeish  · 技术社区  · 5 年前

    我有这种情况:

    #include <vector>
    
    template<typename T, typename U = T>
    U f(T data) {
        return U();
    }
    
    int main() {
        std::vector<int> vec = {1,2,3};
        return f<std::vector<int>, int>(vec);
    }
    

    T U 总是那种 T型 U型 T型 为了不明确 int f 打电话?

    我试过以下方法,但没有成功:

    #include <vector>
    
    template<template<class> class T, class U>
    U f(T<U> data) {
        return U();
    }
    
    int main() {
        std::vector<int> vec = {1,2,3};
        return f<std::vector, int>(vec);
    }
    
    0 回复  |  直到 5 年前
        1
  •  5
  •   NathanOliver    5 年前

    问题是 std::vector 不是只有一个模板参数。它还有一个分配器类型的参数。为了解决这个问题,您可以添加另一个模板参数,或者只使用变量模板参数,比如

    template<template<class...> class T, class U>
    U f(T<U> data) {
        return U();
    }
    

    它将与

    return f<std::vector, int>(vec);
    

    或者更好

    return f(vec);
    

    DR: Matching of template template-arguments excludes compatible templates

    template<template<class> class T, class U>
    U f(T<U> data) {
        return U();
    }
    

    -frelaxed-template-template-args 启用。