0

I have the following piece of code:

File main.cpp:

#include <iostream>
#include "A.h"
class X{};
int 
main()
{   
    X x;
    A<X> a(x);
}   

File A-inl.h

#include <iostream>
template <class T1>
A<T1>::A(T1 t)
{
}
template <class T1>
void A<T1>::foo(T1 t1)
{
}
template <class T1, class T2>
void A<T1>::bar(T1 t, T2 t2)   // Compilation Problem
{
}

File A.h

template <class T1>
class A
{
public:
    explicit A(T1 t1);
    void foo(T1 t1);
    template <class T2>
    void bar(T1 t1, T2 t2); // Compilation Problem
};
#include "A-inl.h"

g++ -g main.cpp

In file included from A.h:11:0,
A-inl.h:14:6: error: prototype for ‘void A<T1>::bar(T1, T2)’ does not     match any in class ‘A<T1>’
void A<T1>::bar(T1 t, T2 t2)
  ^
In file included from main.cpp:3:0:
A.h:8:10: error: candidate is: template<class T1> template<class T2> void A<T1>::bar(T1, T2)
 void bar(T1 t1, T2 t2);

Could you please let me know how do I declare bar? One more question is if at I can create a object A a; I do not know the type of T2 for bar? How will the code for bar get generated.

Thanks

gudge
  • 1,053
  • 4
  • 18
  • 33

1 Answers1

0

Your header declaration is okay; but try doing this in your inline file for the function definition.

template<class T1>
template<class T2>
void A<T1>::bar( T1 t, T2 t2 ) {
}

This now resolves, compiles and build; at least in Visual Studio 2015 Community it does.

This does not work:

template<class T1, class T2>
void A<T1>::bar( T1 t, T2 t2 ) {
}

Because your header declaration is not matching your inline function definition for this is how you declared your template function within your class template:

template<class T2>
void bar( T1 t, T2 t2 );

This is why you need to declare a template<class T1> which is required by the class template, then you need to declare template<class T2> as well for your template function as you declared it within the class template.

Francis Cugler
  • 7,788
  • 2
  • 28
  • 59