C++ template function inside a non-template class [duplicate] - c++

This question already has answers here:
How to create a template function within a class? (C++)
(4 answers)
Closed 7 years ago.
I am looking to start putting in templates in my c++ class code but I have come across a situation I have not experienced before. Basically I have a non-templates class but only 1 function in the class I need to be templated.
class example
{
public:
example();
~example();
<template T> templatefunction(T);
nontemplatefunction(string x);
};
Is this possible? If so, is it a common solution or am I looking at templates completely in error?

As people have noted in the comments, there's no problem doing so.
One aspect to watch out for is where to put the definition of the method templatefunction. For the time being (see the ISO cpp FAQ), you should consider placing it in the header file, which is different than what you'd probably do with the definition of the other methods. Thus you'd have example.hpp:
class example
{
public:
example();
~example();
template<typename T> void templatefunction(T);
void nontemplatefunction(string x);
};
template<typename T> void example::templatefunction(T)
{
}
and then example.cpp:
example::example(){}
void example::nontemplatefunction(string x)
{
}

Related

Template member function failed to call in case if class object is composed-off in other class [duplicate]

This question already has answers here:
Where and why do I have to put the "template" and "typename" keywords?
(8 answers)
Closed 1 year ago.
Template member functions allow us to parameterise functions independently for a class they belong to. They are supported for both template and non-template classes and it worked fine if we directly call it from class object.
But in case if class is composed-off in other class c++ compiler fail to resolve it. In my case I am able to call template member function directly from object but it fails( MsgParser::run(){source.showType();}) when object is composition. logic behind it ?
struct A{};
struct B{};
class DataSource{
public:
template<class Type>
void showType(){
std::cout<<std::endl<<typeid(Type).name();
}
void disp(){ std::cout<<std::endl<<"All OK";}
private:
};
template<class Source>
class MsgParser{
public:
MsgParser(Source &s):source(s){}
void run(){
source.disp();
source.showType<A>(); // failed to call ??
}
private:
Source &source;
};
int main()
{
DataSource dataSource;
dataSource.showType<A>();
MsgParser<DataSource> msgParser(dataSource);
msgParser.run();
return 1;
}
Something like
source.showType < A > (b);
is ambigious to the compiler not knowing yet what kind of template argument you will pass to it. It might as well be a class member showType inside source that is compared to A and b. Therefore you will have to add .template to the call of showType to distinguish it from a comparison
source. template showType<A>();
Try it here!
If you are interested in when to add typename and template refer to this lengthy explanation.

what's the situation that you must use "this" pointer? [duplicate]

This question already has answers here:
Is there any reason to use this->
(16 answers)
Closed 7 years ago.
I have a code working like:
class base {
....
protected:
typeA m_mem;
}
class mymodule: public base{
....
void function(){
m_mem.call();
}
}
This was working OK before. Suddenly, I see it brokes saying "m_mem was not declared...." It might be some other people changed the namespace or other parts.
And I found it was working by just adding "this" then it compiles fine
this->m_mem.call()
While I just would like to know what's the cases that I must use "this" ? I learned "this" can be used to point to distinguish between class member and argument names. While for my case, what can be the reason that I must use "this" for accessing a data member
This can occur for example when you use templates.
The compiler will issue an error that x is an undefined variable for these class definitions
template <class T>
struct A
{
int x;
};
template <class T>
struct B : A<T>
{
void set_x( int v ) { x = v; }
};
If you write
void set_x( int v ) { this->x = v; }
the code will compile.

avoiding template definition in header file [duplicate]

This question already has answers here:
Why can templates only be implemented in the header file?
(17 answers)
Closed 7 years ago.
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
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
}

How to include my implementation in cpp file for some header file (nested classes)

I faced a problem while trying to arrange my project files C++
simply I'm designing a specific template class Mystackt and I want to include entire class inside the public part of Mystackt as an iterator class MyIterator{};
I wrote all of this stuff in my header file MyTemplate.h
so briefly it will appear as following
template <class Type> /* that's in file **MyTemplate.h** */
class MyStackt
{
friend somefunction (int,string,bool);
public:
class iterator
{
public:
iterator();
void somefunc(param1,param2.....);
void otherfunc(...);
private:
Type* ptr;
};
int public_func_of_stackt(void);
void an-otherfunc(int,string,Type,...etc);
private:
int x;
string y;Type* val;
};
Now let's see he cpp file for this header MyTemplate.cpp
I can include the code for all member-functions of Mytemplate class without problems
for example :
template <class Type>
int MyStack<Type>::public_func_of_stackt(void) /*this works perfect*/
{implementation goes here ...;}
but when i am trying to write the implementation of member-functions of entire class (iterator class) the problem starts
template <class Type>
bool MyStackt<Type>::iterator somefunc(param1,param2.....)
{ return current ==rhs.current; }
the question sirs is:
how I can include my code for the member-functions of class iterator inside the Mytemplate.cpp file ?? how should i write that using that external::entire or other specific notation ?
other question :
how can i write (in Mytemplate.cpp file) the implementation for a friend function of class MyStackt ??
update#1 : thank you Veritas
but i also need to know how to define some public function of class MyStackt
if that function is returning iterator type (so it is returning an object of the entire class)
the definition will look something like that
template <class Type>
iterator Stackt<Type>::begin()
{ return *this; } /*this function did not work*/
maybe I need to use some specific notation 4 that ? what if I had a multiple nested classes
waiting for the answer from experts
thank you in advance !
You forgot the scope resolution operator when defining somefunc. The definition should be:
template <class Type>
bool MyStackt<Type>::iterator::somefunc(param1,param2.....)
{
return current == rhs.current;
}
As for the friend function, you define it like any other global function.
To your edit:
The iterator class belongs to the MyStackt's scope so whenever you need to mention it out of MyStackt you need to use the scope operator. As for your question I am not sure what you are trying to do. *this returns the instantiated object which is of type MyStackt.
Also be careful! If you want to seperate your definitions do so using .inl files or similar , not in a cpp file.

avoid code duplication on multiple c++ template spezialization [duplicate]

This question already has answers here:
Why can templates only be implemented in the header file?
(17 answers)
Closed 8 years ago.
I looked around for a good solution to avoid code duplication on each spezialization of a template class.
Here is an example code:
template<class T>
class C
{
int foo();
}
Now the definition for defaults:
template<class T>
C<T>::foo() { return 0; }
Now the spezailization for special templates
template<> C<int>::foo() { ... do a lot of stuff and return n .... }
template<> C<double>::foo() { ... do a lot of stuff and return n .... }
template<> C<int>::foo() { ... do a lot of stuff and return n .... }
Right now I have to duplicate the code for the spezailization. But in general it's the same code.
My questions is:
What is the best solution to avoid code duplication here and how can I hide the implementation ? Maybe by using a noname-namespace or an impl-namespace ?
Kind regards,
Peter
You can do as with any other class: extract the boilerplate code to another (private) function in the template class and call this one in your specializations.
template<class T>
class C
{
int foo();
void bar() { /* does lot of stuff ... */ }
};
template<> int C<int>::foo() { bar(); return n .... }
template<> int C<double>::foo() { bar(); return n .... }
and how can I hide the implementation ? Maybe by using a noname-namespace or an impl-namespace ?
It's not really possible to hide the implementation of template code, by means of having a compilation unit specific unnamed namespace.
If your intend mainly is to get a cleaner readable template header file, you can factor out the implementation to another included file. These are often named .tcc or .icc, there are samples for this technique in most of the c++ implementation standard header files.
One way to avoid duplicating code is to use a base class to handle generic implementation:
template <class T>
class base_C
{
void generic_foo(){...}
};
template <>
class C <SpecialType> : base_C<SpecialType>
{
void foo()
{
SpecialType::custom_foo();
base_C<SpecialType>::generic_foo();
}
};
The idea begind this is to split foo into more generic parts and put them into base_C. With this each specialization of C::foo will have a minimal amount of custom code.