Deduct type of which other type is dependent

前端 未结 1 1682
谎友^
谎友^ 2021-01-22 04:23

I have this situation:

#include 

template
U f(T data) {
    return U();
}

int main() {
    std::vector

        
相关标签:
1条回答
  • 2021-01-22 05:09

    The issue here is std::vector doesn't have just one template parameter. It also has a parameter for the allocator type. To get around that you can add another template parameter, or just use a variadic template template parameter like

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

    which will work with

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

    or even better

    return f(vec);
    

    Do note that this behavior has been changed in C++17. With DR: Matching of template template-arguments excludes compatible templates they relaxed the rules and

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

    will work with gcc in C++17 mode and clang in C++17 with -frelaxed-template-template-args enabled.

    0 讨论(0)
提交回复
热议问题