3

I have the following class defined in a header A.h :

class A {

private:

template<int i>
void method();

};

is there any way for me to keep the implementation of method in its own A.cpp file , with the usual method implementations ? I'm asking this because puting the implementation in a A.h would make the interface very hard to read, especially since it's a private function.

It will only ever be instanciated with a limited values of "i" if that matters

lezebulon
  • 7,607
  • 11
  • 42
  • 73
  • 1
    If you know all the values of `i` that will be used ahead of time, you explicitly instantiate it for every value of `i` you want to allow. – Jerry Coffin Mar 16 '15 at 23:23
  • In the general sense for the specific use of a .cpp file, no. With severe limitations, yes, see: http://stackoverflow.com/questions/115703/storing-c-template-function-definitions-in-a-cpp-file – aruisdante Mar 16 '15 at 23:25
  • If you're only problem with sticking the implementation in the header is readability you can put the implementation in a separate file then include that file at the bottom of the header. – user1937198 Mar 16 '15 at 23:28
  • That duplicate addresses what seems to be your actual need, to separate implementation from interface definition. – aruisdante Mar 16 '15 at 23:28
  • You can declare template as instantiated externally for specified `i`s, and then instantiate it explicitly in some cpp file. See answer to http://stackoverflow.com/questions/22768865/can-i-use-fno-implicit-templates-feature-only-for-one-template . – Frax Mar 16 '15 at 23:46
  • 1
    If you only use the template method inside other non-template members of the A class, then you only need to put the definition of that template in the A.cpp file, because that's the only cpp for which the definition needs to be visible. – Mikael Persson Mar 17 '15 at 00:04

1 Answers1

5

You can do the following (as it's widely used practice):

A.hpp


class A {

private:

template<int i>
void method();

};

#include "A.tcc"

A.tcc


template<int i>
void A::method() {
    // do something with i
}

Note it's important to name the implementation file with a different extension from .cpp actually, because this will confuse most of the standard build system environments (unless you have complete manual selection of translation unit files).


If you want to have specialized implementations for certain values of i, you can provide them as follows:

// Specialization for 1
template<>
void A::method<1>() {
    // do something for specialization with 1
}

template<>
void A::method<2>() {
    // do something for specialization with 2
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190