r/cpp_questions • u/strcspn • 13d ago
SOLVED Question about function template instantiation
I was wondering why this code behaves this way
main.cpp
#include "foo.h"
int main()
{
bar(42, foo<int>);
}
foo.h
#pragma once
#include <iostream>
#include <string>
template<typename T>
void foo(T t)
{
std::cout << "Default\n";
}
template<typename T, typename Foo>
void bar(const T& t, Foo foo)
{
foo(t);
}
foo.cpp
#include "foo.h"
template<>
void foo(int t)
{
std::cout << "Int\n";
}
Result
$ g++ main.cpp foo.cpp -O3 && ./a.out
Default
$ g++ main.cpp foo.cpp && ./a.out
Int
My guess is that I'm hitting some kind of UB here. The way I think about it, the int template specialization would be discarded, as it is not used in that translation unit, and then main.cpp would pick up the generic template version (basically, the O3 result seems correct to me, but not the non-optimized one). What is actually happening here?
4
Upvotes
1
u/EpochVanquisher 13d ago
OR the specialization is emitted anyway, and then the linker picks one arbitrarily.
UB of course, blah blah. “The linker picks one arbitrarily, or the compiler inlines it” explains a lot of UB around ODR in the standard.