Thread: Can I take function names as arguments without using templates?

  1. #1
    Registered User
    Join Date
    Sep 2018
    Posts
    217

    Can I take function names as arguments without using templates?

    STL supposedly does this for functors right, algorithms use identifiers of functions/lambda expressions that return a boolean and get passed two arguments.

    I want to do something similar.
    I could take a function identifier as argument for another function using templates like so:
    Code:
    template <typename T>
    void call_function(T func_name) {
        func_name();
        std::cout << "\n\n" << typeid(T).name();
    // type = bool (__cdecl*)(void)
    }
    
    void print() {
        std::cout << "hey";
    }
    
    int main()
    {
    
        call_function(print);
    
        std::cin.get();
    }
    But how do I do this without templates? Suppose I want to allow only void functions that take no values?

    From that cout statement I got to know that T evaluated to bool (__cdecl*)(void)

    But I can't use bool (__cdecl*)(void) as a type for an argument.
    Last edited by Nwb; 02-21-2019 at 08:01 AM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Use a function pointer parameter, e.g.,
    Code:
    void call_function(void (*func_name)())
    A typedef for the function pointer type may be useful.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File names as function arguments
    By knowNoC in forum C Programming
    Replies: 2
    Last Post: 04-29-2009, 12:15 AM
  2. Pointer to Function(names)
    By Hork83 in forum C++ Programming
    Replies: 3
    Last Post: 08-14-2007, 11:19 AM
  3. Replies: 9
    Last Post: 01-02-2007, 04:22 PM
  4. Getting function names from a module
    By Thantos in forum Windows Programming
    Replies: 2
    Last Post: 01-19-2005, 09:52 AM
  5. Question about Templates and passing arguments
    By supaben34 in forum C++ Programming
    Replies: 2
    Last Post: 10-13-2002, 01:32 AM

Tags for this Thread