1

I am attempting to add a templated method to a templated class. I referred to this answer however the syntax is not working.I added the second method called tester which I would like to be templated. This is what I have

template <typename t,typename u>
struct foo {

    void test();

    template<typename v>
    void tester(v lhs);
};

template<typename t,typename u>
void foo<t,u>::test() {
    std::cout << "Hello World" ;
}

template<typename t,typename u>
template<typename v>
void foo<t,u>::tester<v>(v lhs) {
    std::cout << "Hello world " << lhs ;
}

int main() 
{
    foo<int,int> t;
    t.test();  
    t.tester<int>(12);
}

I am getting the error for method tester this is the error that I get

  main.cpp:20:31: error: non-type partial specialization 'tester<v>' is not allowed
 void foo<t,u>::tester<v>(v lhs) {

Any suggestions on why i am getting this error or what I might be doing wrong ?

James Franco
  • 4,516
  • 10
  • 38
  • 80
  • If you're trying to specialise for `tester` then remove the `typename v` and also use `int` for the `lhs` parameter – KayEss Aug 15 '17 at 05:42
  • I would like to see if I could template the method `tester`. What if later on i would like `lhs` to be of type `string` ? – James Franco Aug 15 '17 at 05:43
  • Then you're not trying to partially specialise, so why do you have `tester` and not `tester`? – KayEss Aug 15 '17 at 05:44
  • I am not trying to partially specialize the method tester.I would like to know if its possible to template a method inside a templated class ? The link says yes – James Franco Aug 15 '17 at 05:46
  • Then you need to remove the `` part. First of all, where did you get the `int` from? And second, you can't do a partial specialisation of a member function, so you want this: `template foo::tester(v lhs) { /*...*/ }` – KayEss Aug 15 '17 at 05:47
  • sorry i just updated my code – James Franco Aug 15 '17 at 05:47
  • @KayEss sorry I just updated my code. I realized i was trying to partially specialize it which was wrong – James Franco Aug 15 '17 at 05:48
  • @KayEss that worked. Its suppose to be `void foo::tester(v lhs) {` I wonder why `void foo::tester(v lhs) {` was not ok – James Franco Aug 15 '17 at 05:51

1 Answers1

1

Comment inline in the corrected code below:

#include <iostream>

template <typename t,typename u>
struct foo {

    void test();

    template<typename v>
    void tester(v lhs);
};

template<typename t,typename u>
void foo<t,u>::test() {
    std::cout << "Hello World" ;
}

/*
 * change made to this template function definition
 */
template<typename t,typename u>
template<typename v>
void foo<t,u>::tester(v lhs) {
    std::cout << "Hello world " << lhs ;
}

int main() 
{
    foo<int,int> t;
    t.test();  
    t.tester<int>(12);
}
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142