9

I am trying to intialize a vector of strings using initializer list. But I am getting some strange behavior. It works if there are more than one argument in the constructor, but gives an error if that is the only argument. Please see the code below to understand

// option.h file

#ifndef __OPTION_H__
#define __OPTION_H__

#include <string>
#include <vector>

namespace CppOptParser {

    class Option
    {
        std::vector<std::string> names;
        std::string description;
    public:
        // constructors
        Option(const std::vector<std::string>& names);
        Option(const std::vector<std::string>& names, const std::string& description);
        // destructor
        ~Option();
    };
} // namespace CppOptParser

#endif /* __OPTION_H__ */


// option.cpp file

#include "option.h"

namespace CppOptParser {

    Option::Option(const std::vector<std::string>& names)
    {
        this->names = names;
    }

    Option::Option(const std::vector<std::string>& names, const std::string& description)
    {
        this->names = names;
        this->description = description;
    }
    Option::~Option() {}

} // namespace CppOptParser


// main.cpp file

#include "option.h"
#include <iostream>

using namespace CppOptParser;

int main(int argc, char *argv[])
{
    Option *opt = new Option({ "f", "filename"}); // gives error -- error C2440: 'initializing' : cannot convert from 'initializer-list' to 'CppOptParser::Option'
    Option *opt1 = new Option({"f", "filename"}, "output file name"); // works fine
    std::cin.get();
    return 0;
}

I am using visual studio 2013. Please help.

10
  • Works on VS2015 Commented Oct 30, 2016 at 9:00
  • @selbie is it visual studio bug then? Commented Oct 30, 2016 at 9:03
  • Do you have the latest service packs for VS2013 installed? Commented Oct 30, 2016 at 9:03
  • On g++ this code doesn't work. Commented Oct 30, 2016 at 9:05
  • For the initializer list {"string1", "string2"}, I suspect visual studio tries to forward directly the char const* to your vector without wrapping it in an initializer list. You made it explicit in your second example thus it works fine. Commented Oct 30, 2016 at 9:05

1 Answer 1

1

You're using old version of C++ compiler. Update your IDE to VS 2015. I tested your program on g++ with option -std=c++11. Your program works in g++ on Linux with option -std=c++11. Without option -std=c++11 your program doesn't work. Newer IDE should support c++11.

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

1 Comment

I tested with VS community 2015 and it seems to work. I also works with g++. Thanks!

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.