Can't assign string literal to boxed std::string vector

前端 未结 3 2007
暖寄归人
暖寄归人 2021-02-13 16:17

This is a simplified version of my type system:

#include 
#include 

template
class Box {
public:
    Box(const T&a         


        
3条回答
  •  长发绾君心
    2021-02-13 16:30

    Looking at your source code in the main function part only:

    int main(int argc, char* argv[]) {
        String a("abc");
        std::vector b = { std::string("abc"), std::string("def") };
    
        // error C2664: 'Box::Box(const Box &)' :
        // cannot convert argument 1 from 'const char' to 'const std::string &'
        std::vector c = { "abc", "def" };
    }
    

    Your first line of code:

    String a("abc");
    

    Is using the typedef version of Box which this class template takes a const T& and since this version of the template is expecting a std::string it is using std::string's constructor to construct a std::string from a const char[3] and this is okay.

    Your next line of code:

    std::vector b = { std::string("abc"), std::string("def") };

    Is a std::vector of the same above. So this works as well since you are initializing the vector with valid std::string objects.

    In your final line of code:

    std::vector c = { "abc", "def" };

    Here are you declaring c as a vector where T is a typedef version of Box however you are not initializing the std::vector with Box types. You are trying to initialize it with const char[3] objects or string literals.

    You can try doing this for the third line: I haven't tried to compile this but I think it should work.

    std::vector c = { String("abc"), String("def") };
    

    EDIT -- I meant to use the constructor for String and not std::string made the appropriate edit.

提交回复
热议问题