Search code examples
c++templatesauto

C++17. Dealing with template parameters that are related using auto . Difficulties with code ordering


I'm creating a class template which takes 2 template parameters but are related. One instantiation will be for a mysql database. The template is initialised with type MYSQL and member functions will return MYSQL_RES *. This works nicely if I create a template with 2 parameters eg

template<class T,class R> class foo

but as the classes are related, when type T is specified, type R is known. Is there any way to code this?

Using auto I can get this to work eg.

template<class T> class foo{
 public:
auto bar();
};

with a member function specialisation given like

 template<> auto foo<MYSQL>::bar(){MYSQL_RES *r;return r;};

but then run into problems with code ordering. ie template<> auto foo::bar has to be implemented before use and not in a separate cpp file.

I've tried doing a forward declaration eg

template<> auto foo<MYSQL_RES>::bar();

but this doesn't work.

Does anyone have a graceful way to solve this problem?

Thanks.


Solution

  • You can create trait to help you:

    template<class T> struct myFooTrait;
    
    template<class T> class foo
    {
    public:
        using R = typename myFooTrait<T>::type;
        R bar();
    };
    
    class MYSQL;
    class MYSQL_RES;
    
    template<> struct myFooTrait<MYSQL>
    {
        using type = MYSQL_RES *;
    };
    
    template<>
    auto foo<MYSQL>::bar() -> R { MYSQL_RES *r = /*..*/;return r;}
    
    // Other specializations...