LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   c++: template member function used in a different templated class (https://www.linuxquestions.org/questions/programming-9/c-template-member-function-used-in-a-different-templated-class-634205/)

matze 04-09-2008 10:58 AM

c++: template member function used in a different templated class
 
Hi,

I've a problem getting the following code to compile (boiled down to the minimum):

Code:

#include <iostream>

class Foo {
public:
  Foo() {};
 
  template<typename T>
  void print() const {
    T con;
    std::cout << "Foo! " << con << std::endl;
  };
};

template<typename S, typename T>
class op : public std::unary_function<T*, void> {
public:
  void operator()(T* t) {
    t->print<S>();
  };
};

int main() {
  op<int, Foo> p;

  p(new Foo());
}

The error g++ gives me is:

Code:

> g++ -o test test.cpp
test.cpp: In member function 'void op<S, T>::operator()(T*)':
test.cpp:18: error: expected primary-expression before '>' token
test.cpp:18: error: expected primary-expression before ')' token

g++ is version 4.1.2 20061115 on a x86_64 debian 4.0. If I change the line

Code:

    t->print<S>();
to

Code:

    t->Foo::print<S>();
the program compiles, but I can't use this... The problem looks like a name resolution problem. I tried to google, but haven't found anything so far. Any suggestions?

Thanks,

matze

ta0kira 04-09-2008 11:10 AM

Why not t->T::print<S>();? I don't see anything fundamental that would keep the name from being resolved, but it is an odd set of circumstances that isn't often used.
ta0kira

matze 04-09-2008 11:21 AM

Thanks, but I tried that and it does not work - it gives an identical error message :(

(The background is that I want to build a generic index where the key is to be defined in the template (just like S is used here) and is retrieved by a method that the used classes (T) share...)

matze

ta0kira 04-09-2008 11:58 AM

Maybe you should use an abstract class instead of a template in Foo? Being an index, there has to be something in common with all of them.
ta0kira

dmail 04-09-2008 12:07 PM

The function is dependant on a template parameter, prefix with template
Code:

  void operator()(T* t) {
    t->template print<S>();
  };


matze 04-10-2008 09:26 AM

@ta0kira: I considered that (or specializing the template), as my classes share a parent class, but that would do it only as a temporary workaround.

@dmail: Thanks, that solved it.

Thanks to both of you for your answers.

matze


All times are GMT -5. The time now is 11:30 PM.