Is there a way to limit the parameter type passed into a method?

  c++

I’m trying to restrict the parameter accepted by a method to one specific user-defined class and haven’t been able to find a way to do this so far.

Is there a way?

This is my code:

class Item {
    public:
        std::string name;  
        Item(std::string n) { name = n; }
}

class Container {

    private:
        std::string name;
        std::string description;
        std::vector<Item> contents;
    
    public:
        Container(std::string n, std::string des) {name = n; description = des;}

        void Container::addItem(Item item) {
            if (typeid(item) == typeid(Item)) {contents.push_back(item);}
        }
}

// code from test file:

WHEN("I try to add something which is not an Item.") {
    std::string helment = "helmet";
    std::vector<Item> contentsBefore = merchant.get_contents();
    merchant.addItem(helmet);    // here a string is added to class attribute "contents" via the above addItem method
    std::vector<Item> contentsAfter = merchant.get_contents();
    THEN("The container should not be updated to add the item.") {
        REQUIRE(contentsBefore == contentsAfter);
    }
}

Source: Windows Questions C++

LEAVE A COMMENT