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.
" 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.
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++.
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.
You can do it in the following way:
template <class T>
template <int CNT>
int A<T>::B<CNT>::doSomething(int in)
{
// do something
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With