Intel® C++ Compiler
Community support and assistance for creating C++ code that runs on platforms based on Intel® processors.

template template parameter

Scheibe__Patrick
New Contributor I
347 Views
Hi,
following short example:
[cpp]template 
class A {
public:
  A():v_(T(0)){};
  T get(){return v_;}
private:
  T v_;
};


template< template class Blub, typename T>
T func(Blub &obj){
  return obj.get();
}

int main(int argc, char **argv)
{
  A obj;
  func(obj);
  return 0;
}[/cpp]
This code is working but what I really want something different.
[cpp]template< template class Blub>
T func(Blub &obj){
  return obj.get();
}
[/cpp]
gives:
tmplateMLPut2.cpp(12): error: identifier "T" is undefined
T func(Blub &obj){
So here my questions: Is the last case valid C++? If yes, why is it not working?
Cheers
Patrick
0 Kudos
3 Replies
Xiaoping_D_Intel
Employee
347 Views
It is invalid. The scope of a template parameter extends from its point of declaration until the end of its template so the scope of "T" will end after the declaration of "Blub".
0 Kudos
Scheibe__Patrick
New Contributor I
347 Views
Thank you for your answer. Does this mean the best I can do is to define func like that:
[cpp]template
and let the compiler deduce the type itself

[cpp]int main(int argc, char **argv)
{  
A obj;  
func(obj);  
return 0;  
}[/cpp]
?

The background of my question is the following: I have an Image class and some typedefs to, say BitImage, ByteImage, etc. and I want to write an ImageSender which is basically an adapter to a C-library to send images over a link. To send an image with the C-library I need 2 things depend on the type T of the image:
  • a string representation of the image type. BitImage->"Bit", etc.... I solved this with specializations of templates:
    [cpp]template <> const char * getImageTypeString(){ return "Bit";}
    template <> const char * getImageTypeString(){ return "Byte";}[/cpp]
  • for every image type T i need to select a different C-function. This is solved the same way with partial specialization.
My sendImage function looks now like

[cpp]template
void sendImage(const Image &img){
  /*use T in getImageString and the send-function ...*/
}[/cpp]
When I have to give the type of sendImage I have to say sendImage(img) which is imho unnatural because I want to send a
BitImage and it would be nicer to call sendImage(..).

Am I on a wrong way? Any ideas?

Cheers
Patrick
0 Kudos
Xiaoping_D_Intel
Employee
347 Views
Compiler can deduce the type itself:


BitImage img;

sendImage(img); // Compiler will select getImageTypeString to return "Bit" if getImageTypeString called inside.

0 Kudos
Reply