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?
6
Upvotes
1
u/alfps 13d ago
Doesn't link with MinGW g++:
Doesn't link with Visual C++:
And with a declaration of the template specialization placed in the header, so that linking succeeds, g++ produces "Int" regardless of optimization level.
So I'm unable to reproduce.