Reputation: 424
so this works fine:
template<class V>
void bar(V v1, V v2) {
}
template <class T>
void foo(T t1, T t2) {
bar(t1, t2);
}
int main() {
foo(5, 6);
}
but if i change the order of foo and bar like this:
template <class T>
void foo(T t1, T t2) {
bar(t1, t2);
}
template<class V>
void bar(V v1, V v2) {
}
int main() {
foo(5, 6);
}
i get a compilation error:
see reference to function template instantiation 'void foo(T,T)' being compiled
Error C3861 'bar': identifier not found 'bar':
'bar' function was not declared in the template definition context and can be found only via argument-dependent lookup in the instantiation context
what is causing this? what is the hidden problem? what rule of cpp have i broke this time?
I will appreciate insights on the matter
EDIT:
thank you for your comments, but for some reason changing bar to swap cause error:
this code:
template<class V>
void swap(V v1, V v2) {
}
template <class T>
void foo(T t1, T t2) {
swap(t1, t2);
}
int main() {
foo(5, 6);
}
generates this error:
while trying to match the argument list '(T, T)' see reference to function template instantiation 'void foo(T,T)' being compiled
or 'void std::swapstd::ios_base::iostate,0(_Ty &,_Ty &) noexcept' could be 'void swap(V,V)' Error C2668 'swap': ambiguous call to overloaded function
I know that swap is not a key word in c++.
What is causing this error? i have written this code in a brand new project and it still doesn't work
Upvotes: 2
Views: 1800
Reputation: 122955
You would get a compiler error from this code for the very same reason:
void foo(T t1, T t2) {
bar(t1, t2);
}
void bar(V v1, V v2) {
}
int main() {
foo(5, 6);
}
You cannot call bar
before it is declared. Solutions: Either declare bar
before you call it, or move the whole definition of bar
before foo
.
Upvotes: 2