C++ vector emplace_back fail with piecewise_construct

Viewed 35

I was trying to use C++ std::vector's emplace_back (along with std::piecewise_construct and std::forward_as_tuple) on a vector of tuple, but compiler complain about template argument deduction/substitution failure. However, if I change the data structure to a vector of pair, the code compiles. Could you guys help me understand and resolve the issue?

Code to reproduce the issue:

#include <iostream>
#include <vector>
#include <tuple>

using namespace std;

struct TestObj {
    TestObj() = delete;
    TestObj( vector<int> &v1, vector<int> &v2 ) {
        d1 = v1;
        d2 = v2;
        cout << "called ctor \n";
    }
    
    vector<int> d1;
    vector<int> d2;
};

int main()
{
    vector<int> a1 {1, 2, 3};
    vector<int> a2 {1, 2, 3};
    vector<TestObj> t1;
    t1.emplace_back(a1, a2);
    vector<std::pair<TestObj, TestObj> > t2;
    t2.emplace_back(std::piecewise_construct, forward_as_tuple(a1,a2), forward_as_tuple(a2,a2) );
    vector<std::pair<int*, TestObj> > t3;
    t3.emplace_back(std::piecewise_construct, forward_as_tuple( nullptr ), forward_as_tuple( a1, a2 ) );
    // vector<std::tuple<int*, TestObj> > t4;
    // t4.emplace_back(std::piecewise_construct, forward_as_tuple( nullptr ), forward_as_tuple( a1, a2 ) );
}

t3 can compile, however t4 failed.

I understand that I can put the int* as a member variable of TestObj to avoid the use of tuple or pair, but I'm curious why vector of pair could work in this case while vector of tuple can't.

0 Answers
Related