2

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.

Mint
  • 21
  • 2
  • 1
    std::tuple doesn't have a c'tor dispatched by `std::piecewise_construct_t` – StoryTeller - Unslander Monica Nov 04 '21 at 23:21
  • 1
    @StoryTeller-UnslanderMonica Thanks for your quick response! After you pinpoint the reason, found there were previous discussion about this on SO: https://stackoverflow.com/questions/11846634/why-is-there-no-piecewise-tuple-construction. – Mint Nov 04 '21 at 23:33
  • Not that you wonder: I recorded the duplicate found by yourself in a close-vote... ;-) – Scheff's Cat Nov 05 '21 at 05:57
  • ...and an up-vote as a cheer-up. Beyond being a duplicate, this is one of the better first questions I've seen so far. ;-) – Scheff's Cat Nov 05 '21 at 05:59

0 Answers0