Search code examples
c++templatesargumentsdefault-arguments

Default argument with template in C++


I'm designing an interface, by which users can define a class that tells what they want to do.
The code is something like the following,

#include <stdio.h>

class Dummy{
public:
    void do(){ printf("do nothing\n"); }
};

class Task{
public:
    void do(){ printf("do something\n"); }
};

template <class TASK>
void func(TASK &task = Dummy()){
    task.do();
}

int main(){
    func(); // do nothing
    Task task;
    func(task); // do something
}

How to make it work?


Solution

  • The main issue is this func argument:

    TASK &task = Dummy()
    

    It will not work unless it is const. This happens because non-const lvalue reference to type cannot bind to a temporary.

    But if you can use const there, you can easily solve your problem:

    class Dummy{
    public:
        void doit() const { printf("do nothing\n"); }
    };
    
    class Task{
    public:
        void doit() const { printf("do something\n"); }
    };
    
    template <class TASK = Dummy>
    void func(const TASK &task = TASK()){
        task.doit();
    }
    
    int main(){
        func(); // do nothing
        Task task;
        func(task); // do something
    }