I want to define a function template of a class template. The code looks like this.
template<int M>
struct test{
private:
int value;
template<int N = 2 * M>
friend auto foo(test const t){
test<N> r;
r.value = t.value;
return r;
}
};
int main(){
test<1> t;
foo(t);// expected to return test<2>
foo<1>(t);// expected to return test<1>
foo<3>(t);// expected to return test<3>
}
But it won't compile. Compared with previous problems, the following lists the differences.
- The result of the function template involves another instatiation of the class template. It seems that the function template has to be defined outside. But I am not sure.
- The function template uses default template arguments. So, if the function template is defined outside the class, a helper function template is required.
Compiling Errors with g++ -std=c++1z
:
a.cpp: In instantiation of 'auto foo(test<M>) [with int N = 2; int M = 1]':
a.cpp:16:10: required from here
a.cpp:4:9: error: 'int test<2>::value' is private
int value;
^
a.cpp:9:17: error: within this context
r.value = t.value;
^
a.cpp: In instantiation of 'auto foo(test<M>) [with int N = 3; int M = 1]':
a.cpp:18:13: required from here
a.cpp:4:9: error: 'int test<3>::value' is private
int value;
^
a.cpp:9:17: error: within this context
r.value = t.value;
^
A possible workaround, yet not correct either.
template<int M>
struct test{
private:
int value;
template<int NA, int NR>
friend test<NR> foo_impl(test<NA> const&);
};
template<int NA, int NR>
test<NR> foo_impl(test<NA> const& t){
test<NR> r;
r.value = t.value;
return r;
}
template<int NR, int NA>
auto foo(test<NA> const& t){
return foo_impl<NA, NR>;
}
template<int NA>
auto foo(test<NA> const& t){
return foo_impl<NA, NA * 2>(t);
}
int main(){
test<1> t;
foo(t);
foo<3>(t);
foo<1>(t);
}
Error:
t.cpp: In function 'int main()':
t.cpp:31:13: error: call of overloaded 'foo(test<1>&)' is ambiguous
foo<1>(t);
^
t.cpp:18:6: note: candidate: auto foo(const test<NR>&) [with int NR = 1; int NA = 1]
auto foo(test<NA> const& t){
^
t.cpp:23:6: note: candidate: auto foo(const test<NA>&) [with int NA = 1]
auto foo(test<NA> const& t){
^