CodexBloom - Programming Q&A Platform

GCC 12.1.0 Generates Incorrect Code for Template Specialization with Variadic Templates

👀 Views: 12 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
gcc c++ templates variadic-templates C++

I'm maintaining legacy code that I've been banging my head against this for hours... I'm using GCC 12.1.0 to compile a C++ project that heavily relies on variadic templates and template specialization. I've encountered a strange scenario where my specialized template methods seem to generate incorrect code, leading to unexpected behavior at runtime. Here's a simplified version of my code: ```cpp #include <iostream> template <typename T> struct MyStruct { void func(T arg) { std::cout << "Generic: " << arg << std::endl; } }; template <typename... Args> struct MyStruct<int, Args...> { void func(int arg) { std::cout << "Specialized: " << arg << std::endl; } }; int main() { MyStruct<int, double> m; m.func(42); // Should call the specialized func m.func(3.14); // Should call the generic func return 0; } ``` When I run the code, I expect `m.func(42);` to call the specialized function, but I get the generic function output instead: ``` Generic: 42 ``` This happens only when I compile with optimizations enabled (`-O2` or higher). When I compile without optimizations, it works as expected. I have tried using various optimization flags like `-O1`, `-O2`, and even `-fno-inline`, but the scenario continues. Additionally, I verified that the function signatures are correct, and I've checked for any potential name mangling issues. Is this a known scenario with GCC 12.1.0, or am I missing something in my template specialization? Any help would be appreciated! I'm working on a service that needs to handle this. I'm working on a CLI tool that needs to handle this. Any ideas how to fix this? Hoping someone can shed some light on this.