Search code examples
c++templatesvectorauto

How to create a template which gets input variables in square brackets?


First of all, I know my question is too bizarre due to English is not my mother tongue.

I have used Google to learn this but I did not understand anything actually.

I want to create a function like this:

The function should take two parameters in square brackets and should get a parameter with assignment (=) operator.

I want to a function like this:

myFunction[Parameter1][Parameter2] = Parameter3;

Parameter1 and Parameter2 are integers. Parameter3 is a string.

And here is an example that describes what I want:

myFunction[3][5] = "stackoverflow";

How do I create that kind function?


Solution

  • You can do something like this:

    #include <iostream>
    #include <functional>
    
    using FuncType=std::function<void(int, int, std::string)>;
    
    class SubSubFunction {
    public:
        SubSubFunction(FuncType func, int arg1, int arg2) : func_(func), arg1_(arg1), arg2_(arg2) {}
        SubSubFunction& operator =(std::string arg) {
            func_(arg1_, arg2_, arg);
            return *this;
        }
    private:
        FuncType func_;
        int arg1_;
        int arg2_;
    };
    
    class SubFunction {
    public:
        SubFunction(FuncType func, int arg1) : func_(func), arg1_(arg1) {}
        SubSubFunction operator [](int arg) {
            return {func_, arg1_, arg};
        }
    private:
        FuncType func_;
        int arg1_;
    };
    
    class Function {
    public:
        Function(FuncType func) : func_(func) {}
        SubFunction operator [](int arg) {
            return {func_, arg};
        }
    private:
        FuncType func_;
    };
    
    int main()
    {
        Function myFunction([](int arg1, int arg2, std::string arg3){
            std::cout << "Arg1: " << arg1 << ", arg2: " << arg2 << ", arg3: " << arg3 << std::endl;
        });
        myFunction[3][5] = "stackoverflow";
    }