2

Here is my code:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

template<int N>
class Arguments
{
protected:
    string arguments[N];
public:
    Arguments(const string(&arg)[N]) : arguments{ arg } {}
    string operator[](const int &i) const { return arguments[i]; }
};

int main()
{
    string arr[3] = { "arg1", "arg2", "arg3" };
    Arguments<3> args(arr);

    cout << args[2];

    return 0;
}

This is the error i get:

Severity    Code    Description Project File    Line    Suppression State
Error   C2440   'initializing': cannot convert from 'const std::string [3]' to 'std::string'    
coursework_draft    C:\dev\coursework_draft\coursework_draft\coursework_draft.cpp   13  

What do i need to change?

2
  • 4
    You can't initialize an array with another array, only elementwise. Either use a loop to copy the elements, or use std::array which can be copied normally. Commented May 19, 2020 at 16:59
  • I fixed it. Thank you! Commented May 19, 2020 at 17:06

3 Answers 3

5

Arrays are not copyable in C++. So this is never going to work

 Arguments(const string(&arg)[N]) : arguments{ arg } {}

You could use std::array<std::string, N> instead, or you could copy the array element by element in the body of the constructor.

Sign up to request clarification or add additional context in comments.

7 Comments

fixed it. Thank you!
Arguments(const string(&arg)[N]) : arguments( arg ) {} seems to work also... what is wrong with it?
@Klaus It's not legal C++. g++ is using a non-standard extension to allow it to compile
@NathanOliver: Compiles also with -pedantic which should warn on such extensions... OK, it is like it is :-) Thanks!
@Klaus Seems like a bug in GCC.
|
1

This:

arguments{ arg }

is list-initialisation and means that the first element of arguments is initialised with arg. But the elements of arguments are std::string, which cannot be initialised with an array of strings.

Arrays are not copy-initialisable.

Classes however can be copy initialisable, and they can have array members. As such, you can use a class as a wrapper around an array that can be conveniently copied. The standard library has a template for such array wrapper. Its name is std::array.

Another option is to copy the array in the constructor body using std::copy or similar function.

1 Comment

fixied it. Thank you!
0

You can use std::copy:

Arguments(const string(&arg)[N]) {
   std::copy(arg, arg + N, arguments); 
}

Here's a demo.

3 Comments

i had those. the compiler said to use { } to initialize an array
This might work with g++ but it wont with clang and is not standard
@NathanOliver Oh, I didn't know that. thanks, edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.