2016-04-04 37 views
0

我有以下代碼:鑄造的std :: wstring的爲const wchar_t的X []

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}); 
     } 
    } 
} 

正如你可以看到代碼

 db::statement st(con, sql); 

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

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

在if-else語句寫得複製。我想移動那部分,如果其他情況外是這樣的:

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}); 
    } 
} 

我已經試過在的if-else情況下使用臨時std::wstring更換sql[],但我想不出怎麼投std::wstringconst wchar_t sql[]

回答

3

std::wstring有一個成員函數c_str,它將返回const wchar_t*到底層字符串。只要db::statement需要const wchar_t []const wchar_t *那麼你可以使用

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

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

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

謝謝,我知道c_str(),但沒想到做這樣的。謝謝!你知道一個可以閱讀C++類型的網站嗎?我是新的c + +遊戲我的知識主要是在c# –

+0

@PresidentCamacho我使用[cppreference.com](http://en.cppreference.com/w/)相當多。你可能也想得到一個不錯的[C++書](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver

相關問題