2017-01-07 39 views
1

是否有可能建立一個std ::對,如果我要構建嵌入式的std :: string有一個構造函數超過1周的說法?使用非單參數ctor初始化嵌入在std :: pair中的std :: string?

例如,這是合法的:

#include <iostream> 
#include <utility> 
#include <string> 

int main() 
{ 
    std::pair<int, int> pair(2, 3); 
    return 0; 
} 

...這是合法的:

#include <iostream> 
#include <utility> 
#include <string> 

int main() 
{ 
    std::pair<int, std::string> pair(2, "hello"); 
    return 0; 
} 

...但我不知道是否像以下是可能的:

#include <iostream> 
#include <utility> 
#include <string> 

int main() 
{ 
    std::pair<int, std::string> pair{2, {"hello", 3}}; //Unclear if some variation/combination of parentheses and curly braces can make this legal. 
    return 0; 
} 

認爲上面是正確的語法使用「統一初始化列表」,但是這不適用於我的目的,因爲我使用的是C++ 11之前的編譯器。有什麼方法可以用C++ 11之前的語法來解決這個問題嗎?

爲了澄清,我想用這個的std :: string構造函數:

basic_string(const CharT* s, 
       size_type count, 
       const Allocator& alloc = Allocator()); 

至於爲什麼我問這個背景下,這是學術的好奇心(如果錯了指正):我認爲這樣做的單線建設更有效率,因爲std::pair及其成員只需創建並初始化即可。而如果我做了這樣的事情(使用C++語法11)...

#include <iostream> 
#include <utility> 
#include <string> 

int main() 
{ 
    std::pair<int, int> pair(2, 3); 
    std::pair<int, std::string> pair2 = {2, {"hello", 3}}; 
    return 0; 
} 

...然後我在技術上創造了std::pair<int, std::string>其成員都是默認池莉構建,然後通過調用std::pairoperator= ,然後在對的成員上調用operator=

+0

'的std :: string( 「你好」,3)'?你想使用哪個構造函數?爲什麼? – Charles

+0

@ c650:更新後回答您的問題。 – StoneThrow

回答

2

只要寫

std::pair<int, std::string> pair(2, std::string("hello", 3)); 

至於這個聲明

std::pair<int, std::string> pair2 = {2, {"hello", 3}}; 

那麼實際上就相當於這個聲明

std::pair<int, std::string> pair{2, { "hello", 3}}; 

由於拷貝構造函數省音。考慮到既沒有賦值運算符,因爲它是一個聲明。

考慮下面的例子

#include <iostream> 
#include <string> 

int main() 
{ 
    struct Pair 
    { 
     std::string s; 
     int i; 
     Pair(int i, const std::string &s) : i(i), s(s) 
     { 
      std::cout << "Pair(int, std::string)" << std::endl; 
     } 

     Pair(const Pair &p) : i(p.i), s(p.s) 
     { 
      std::cout << "Pair(const Pair &)" << std::endl; 
     } 
    }; 

    Pair p1{ 2, { "hello", 3 } }; 
    Pair p2 = { 2, { "hello", 3 } }; 
} 

程序輸出是

Pair(int, std;:string) 
Pair(int, std;:string) 
+0

我想這回答我的問題,但我仍然好奇:這可能與前C++語法11不使用中間的std :: string對象? – StoneThrow

+0

@StoneThrow不,這是不可能的。 –

+0

所以,維拉德,用C++ 11的語法,由於複製省略,構建該對的兩種方法是相同的效率,是嗎?即我對默認構造的假設,後面跟着'operator ='的多次調用是不正確的,對嗎? – StoneThrow

相關問題