Search code examples
c++typestypename

Why c++ don't infer template argument T for simple nested types variables?


In this piece of code:

#include <iostream>
#include <vector>
#include <utility>

template <typename T>
using Separation = std::pair<std::vector<T>, std::vector<T>>;

int main()
{
    std::vector<int> vector1 = {1};

    Separation s1(vector1, vector1);

    std::cout << s1.first[0];

    return 0;
}

The g++ compiler says: error: missing template arguments before ‘(’ token

That can be fixed just by adding the template parameter to Separation. But, if v1 is a vector of integer, shouldn't the compiler be able to understand that T should be generic that comes from the vector??


Solution

  • If you can make it a subtype, you may add a deduction guide:

    #include <iostream>
    #include <vector>
    #include <utility>
    
    template <typename T>
    struct Separation : std::pair<std::vector<T>, std::vector<T>> {
        using std::pair<std::vector<T>, std::vector<T>>::pair;
    };
    
    template <class T>
    Separation(std::vector<T>, std::vector<T>) -> Separation<T>;
    
    int main()
    {
        std::vector<int> vector1 = {1};
    
        Separation s1(vector1, vector1); // works fine
    
        std::cout << s1.first[0];
    
        return 0;
    }