Home > Enterprise >  C function template initialization?
C function template initialization?

Time:08-27

I'm not sure if this title reflects the question. Here's a template function. My question is

what does s(...) in the code below mean since compiler doesn't know what class Something is and the compiler doesn't even complain.

I don't quite understand what's going on. Thanks

template <class Something>
void foo(Something s)
{
    s(0, {"--limit"}, "Limits the number of elements.");  //What does this mean?
    
    s(false, {"--all"}, "Run all");
}

CodePudding user response:

what does s(...) in the code below mean

It means that you're trying to call s while passing different arguments 0, {"--limit"}, "Limits the number of elements. For example, s might be of some class-type that has overloaded the call operator operator() that takes variable number of arguments.

So by writing:

s(0, {"--limit"}, "Limits the number of elements."); //you're using the overloaded call operator() for some given class type

In the above, you're using the overloaded call operator() and passing different arguments to it.

Lets look at a contrived example:

struct Custom 
{
  //overload operator()
  template<typename... Args> 
  void operator()(const Args&...args)
  {
      std::cout << "operator() called with: "<<sizeof...(args)<<" arguments"<<std::endl;
  }
};

template <class Something>
void foo(Something s)
{
    s(0, "--limit", "Limits the number of elements.");  //call the overloaded operator()
    
    s(false, "--all", "Run all", 5.5, 5);              //call the overloaded operator()
}
int main()
{
    Custom c;      //create object of class type Custom
    foo(c);       //call foo by passing argument of type `Custom`
}

Demo

CodePudding user response:

Looks like the intention of foo is to accept a class that has a call operator.

Eg

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

struct ReallySomething {
    void operator()(bool b, const std::vector<std::string>& flags, const std::string& description)
    {
        std::cout << "Condition is " << (b ? "true" : "false") << std::endl;
        std::cout << "Number of flags: " << flags.size() << std::endl;
        std::cout << "Description: " << description << std::endl;
    }
};

template <class Something>
void foo(Something s)
{
    s(0, {"--limit"}, "Limits the number of elements.");  //What does this mean?
    
    s(false, {"--all"}, "Run all");
}

int main()
{
    ReallySomething r;
    foo(r);

    return 0;
}

Then

s(false, {"--all"}, "Run all");

and

s(0, {"--limit"}, "Limits the number of elements.");

will call this function.

Try the code here

  •  Tags:  
  • c
  • Related