2

How do you instantiate a template member function of a template class without making a dummy call to it?

So imagine a header: class.h

#pragma once

template<class T>
class A {
public:

    template<class R>
    T b(R r);  
};

class.cc

#include <limits>
#include "class.h"

template<class T> template<class R> T A<T>::b(R r)
{
    /* Some code */
    return std::numeric_limits<R>::max() - r;
}

void dummy()
{
    A<int> a;
    a.b<short>(2);
}

And some test file:

#include <iostream>
#include "class.h"

using namespace std;

int main(){

    A<int> a{};
    auto ans = a.b<short>(2);
    cout << ans << " " << sizeof(ans) << endl;
}

How do I force the compiler to compile A<int>::b<short>(short) without calling it in class.cc (and thus having a dummy function laying around) or putting everything in the header (and having to recompile alot of code all the time).

I've tried different forms of template A<int>; and template <> template <> int A<int>::b(short) in the cc-file but I can't make up the right syntax.

Vilhelm
  • 717
  • 1
  • 7
  • 12

1 Answers1

2

You can do it with this:

template int A<int>::b<short>(short r);
geza
  • 28,403
  • 6
  • 61
  • 135
  • 1
    FWIW the function parameter name is not needed. – NathanOliver Apr 25 '19 at 19:36
  • @NathanOliver: Yes. I think this is personal preference. I tend to keep parameter names in a lot of places where it is not mandatory. But maybe here it doesn't add anything useful, though. – geza Apr 25 '19 at 19:40
  • Thanks, it compiles. I really need to wrap my head around template syntax. Was trying for like 2h without any success ... is that row a forward declaration or how should you think about it? I probably put things in the wrong order in the cc-file. – Vilhelm Apr 25 '19 at 20:08
  • 1
    @Vilhelm: No. It is called "explicit template instantiation". Your first attempt `template A;` is an (class) explicit template instantiation (but it cannot instantiate the template function inside). Your second attempt with the `template <>` is explicit specialization. I recommend you to skim through http://eel.is/c++draft/temp.spec. – geza Apr 25 '19 at 20:21