Как я могу заполнить вектор своими функциями? - PullRequest
0 голосов
/ 29 марта 2020
#include <iostream>
#include<string>
#include<vector>
#include<functional>
using namespace std;
void straightLineMethod();
void unitsOfActivity();
void decliningMethod();

int main()
{
    using func = std::function<void()>;
    string inputMethod;
    string depreciation[3] = { "straight line","units of activity","declining" };
    std::vector<func> functions;
    functions.push_back(straightLineMethod);
    functions.push_back(unitsOfActivity);
    functions.push_back(decliningMethod);
    cout << " Enter the method of depreciation you're using: " << depreciation[0] << ", " << depreciation[1] << " , or " << depreciation[2] << endl;
    cin.ignore();
    getline(cin, inputMethod);
    for (int i = 0; i <functions.size() ; i++) {
        while(inputMethod == depreciation[i])
        {
            functions[i]();
        }
}

Я попытался найти ответ и узнал об использовании std::function, но я не до конца понимаю, что он делает. Довольно сложно найти ответ на этот вопрос в Интернете. По сути, я хочу, чтобы три функции были помещены в вектор, сравнили пользовательский ввод с массивом строк, а затем использовали индекс в массиве, чтобы использовать коррелирующий индекс в векторе для вызова функции. Это показалось мне хорошей идеей, но она провалилась. И использование .push_back для заполнения вектора в этом случае дает мне

E0304 error:  no instance of overloaded function matches the argument list. 

Edit: Specifically, I dont know what the syntax: using func= std::function<void()> is actually doing. I just added it to the code to try to get it to work , thats why my understanding is limited in troubleshooting here.

Edit: the E0304 error is fixed by correcting the syntax to reference the function instead of calling it. And i changed functions[i] to functions[i]() to call the functions, although it is still not working.

1 Ответ

0 голосов
/ 29 марта 2020

Похоже, вы перепутали синтаксис вызова функции и передали фактическую (ссылку на a) функцию. В вашем functions.push_back(functionNameHere) удалении внутреннего (), вы не хотите вызывать эту функцию, вы хотите поместить sh саму функцию в вектор. С другой стороны, ваш functions[i] должен быть functions[i](), потому что здесь вы на самом деле вызываете функцию.

Например, это определенно работает:

void testMethod() 
{
    cout << "test method has been called\n";
}

int main()
{
    using func = std::function<void()>;
    std::vector<func> functions;
    functions.push_back(testMethod);
    functions[0]();
}

Смотрите его здесь - http://cpp.sh/2xvnw

...