Pimpl Idiom with template member function

Viewed 1956

I want to use the Pimpl Idiom but I'm having a problem that one of the member functions is template function so it has to be implemented in a header file.

For example this below works fine of course

//Foo.h
class Foo{
    struct Impl;
    Impl* ptr;
public:
    Foo();
    void bar(int);
    ~Foo();
};


//Foo.cpp
struct Foo::Impl{
    void bar(int i){ std::cout << "i = " << i << std::endl; }
};

Foo::Foo() : ptr{new Impl}{}
void Foo::bar(int i){ ptr->bar(i); }
Foo::~Foo(){ delete ptr; }

but is there any way to implement something similar if bar is a template function?

//Foo.h
class Foo{
    struct Impl;
    Impl* ptr;
public:
    Foo();
    template<typename T>
    void bar(T);
    ~Foo();
};

template<typename T>
void Foo::bar(T val)
{
    /*has to be implemented in a header but I cant call member function 
    on an incomplete type*/
    ptr->bar(val); //error
}

//Foo.cpp
struct Foo::Impl{
    template<typename T>
    void bar(T val){ std::cout << "val = " << val << std::endl; }
};
//...

EDIT

After reading R Sahu's answer and by the looks of all the other comments I figured to do something like it was suggested to me. Explicit template instantiation in a .cpp file seemed like the most clearest option so here is the code if anyone is interested. Thanks to everyone who answered!

//Foo.h
class Foo{
    struct Impl;
    Impl* ptr;
public:
    Foo();
    template<typename T>
    void bar(T);
    ~Foo();
};


//Foo.cpp
struct Foo::Impl{
    template<typename T>
    void bar(T val){ std::cout << "val = " << val << std::endl; }
};

template<typename T>
void Foo::bar(T val)
{
    ptr->bar(val);
}

Foo::Foo() : ptr{ new Impl}{}
Foo::~Foo(){ delete ptr; }

#define instantiate_template_function(type)\
    template void Foo::bar(type);

instantiate_template_function(int)
instantiate_template_function(double)
instantiate_template_function(char)
instantiate_template_function(float)
instantiate_template_function(long long)
1 Answers
Related