Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble with template classes having template member functions

Tags:

c++

In my experimentation with templates I've come across a confusing predicament. I'm defining a templated struct F who default argument is int. It has a templated member function g. I'm defining it below the struct definition. I figured this was the correct way to go about it, however, I receive an error. And only one error:

prog.cpp:9:62: error: default argument for template parameter for class enclosing 'void F< >::g()'

template <typename = int> struct F {

    template <typename> void g();

};

template <typename T = int> template <typename> void F<T>::g() {}

int main() {

    F<>f;

}

It's quite vague. I couldn't exactly understand what it means. So I tried changing some things around. I figured it was the default template arguments for the definition of F. So I changed:

template <typename = int> struct F {

to

template <typename T = int> struct F {

I also tried giving g template arguments:

template <typename T = int> template <typename U> void F<T>::g<U>() {}

But then I received the errors:

prog.cpp:9:67: error: function template partial specialization 'g' is not allowed
prog.cpp:9:67: error: default argument for template parameter for class enclosing 'void F::g()'

I even tried specifying that g was a template function:

template <typename T = int> template <typename U> void F<T>::template g<U>() {}

But it didn't help. What am I doing wrong?

like image 468
David G Avatar asked Jan 15 '23 06:01

David G


1 Answers

Default template parameters must be used only on function declarations, not on definitions:

template <typename T/* = int*/> template <typename> void F<T>::g() {}
like image 89
mfontanini Avatar answered Feb 18 '23 20:02

mfontanini