Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate definition and declaration of child template class

If I have a template class defined as:

#ifndef A_HPP
#define A_HPP

template<class T>
class A
{
public:
  int doSomething(int in, bool useFirst);

private:
  template<int CNT>
  class B
  {
  public:
    int doSomething(int in);
  };

  B<2> first;
  B<3> second;
};

#include "a_imp.hpp"

#endif

Now I can go about having a declaration for A::doSomething in an implementation header file like this

#ifndef A_IMP_HPP
#define A_IMP_HPP

template<class T>
int A<T>::doSomething(int in, bool useFirst)
{
  if (useFirst)
    return first.doSomething(in);
  return second.doSomething(in);    
}

#endif

However I do not know how I go about making the declaration for the child class's method. Is it even possible or do I have to do one of the other two ways I can think of doing this, namely defining the methods in the main header or declare the class outside of A.

Please note that I am using C++11 so if this is only doable in that it will still work for me, though a C++98 solution would be good for other people.

like image 384
lmcdowall Avatar asked Mar 13 '14 21:03

lmcdowall


People also ask

What does template typename t mean?

" typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.

How to define template class in cpp?

Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. To simply put, you can create a single function or single class to work with different data types using templates. C++ template is also known as generic functions or classes which is a very powerful feature in C++.

How a template is declared?

A class template must be declared before any instantiation of a corresponding template class. A class template definition can only appear once in any single translation unit. A class template must be defined before any use of a template class that requires the size of the class or refers to members of the class.


2 Answers

You can do it in the following way:

template <class T>
template <int CNT>
int A<T>::B<CNT>::doSomething(int in)
{
    // do something
}
like image 106
Constructor Avatar answered Sep 29 '22 09:09

Constructor


Not sure if this is what you're asking, but I guess you need something like this:

 template<class T>
 template<int CNT>
 int A<T>::B<CNT>::doSomething(int in)
 {
    return /*...*/;
 }

Note that the template keyword appears twice, first for the template parameters of A, then for the parameters of nested class B.

like image 31
iavr Avatar answered Sep 29 '22 07:09

iavr