President Camacho
President Camacho

Reputation: 1910

Casting std::wstring to const wchar_t x[]

I have the following code:

void get_id(int i, std::vector<item>& _items) {

    auto cpool = get_db_connection_pool();
    auto con = cpool->get_connection();
    db::result m;

    int _id;

    if (i == 1) {               

        const wchar_t sql[] = LR"***(
            SELECT * FROM TABLE1                    
        )***";

        db::statement st(con, sql);

        m = st.execute().into(_id);

        while (m.move_next()) {                 
            _items.push_back(item {_id});
        }
    }
    else {
        const wchar_t sql[] = LR"***(
            SELECT * FROM TABLE2                    
        )***";

        db::statement st(con, sql);

        m = st.execute().into(_id);

        while (m.move_next()) {                 
            _items.push_back(item {_id});
        }
    }
}

As you can see the code

        db::statement st(con, sql);

        m = st.execute().into(_id);

        while (m.move_next()) {                 
            _items.push_back(item {_id});
        }

is written duplicated in the if-else statement. I would like to move that part outside of the if else case like this:

void get_id(int i, std::vector<item>& _items) {

    auto cpool = get_db_connection_pool();
    auto con = cpool->get_connection();
    db::result m;

    int _id;

    if (i == 1) {               

        const wchar_t sql[] = LR"***(
            SELECT * FROM TABLE1                    
        )***";
    }
    else {
        const wchar_t sql[] = LR"***(
            SELECT * FROM TABLE2                    
        )***";
    }


    db::statement st(con, sql);

    m = st.execute().into(_id);

    while (m.move_next()) {                 
        _items.push_back(item {_id});
    }
}

I've tried replacing sql[] in the if-else case with a temporary std::wstring but I can't figure out how to cast std::wstring to const wchar_t sql[].

Upvotes: 0

Views: 424

Answers (1)

NathanOliver
NathanOliver

Reputation: 180585

std::wstring has a member function c_str that will return a const wchar_t* to the underlying string. As long as db::statement takes a const wchar_t [] or const wchar_t * then you can use

std::wstring sql;
if (i == 1) {               

    sql = LR"***(
        SELECT * FROM TABLE1                    
    )***";
}
else {
    sql = LR"***(
        SELECT * FROM TABLE2                    
    )***";
}

db::statement st(con, sql.c_str());

Upvotes: 3

Related Questions