Thursday, February 3, 2022

[SOLVED] msvc and gcc different behavior

Issue

#include <iostream>
template<typename T>
const T unit{ 1 };

template<typename T>
struct data
{
    typename T::value_type val;
};

struct decimal_def
{
    using  value_type = int;
    static const value_type unit_val() {
        return 10;
    }
};

template<typename T>
const data<T> unit<data<T>> { T::unit_val() };

auto decimal_data_unit = unit<data<decimal_def>>;

int main(){
    std::cout << decimal_data_unit.val << std::endl;
    return 0;
}

exoect: 10
gcc: 10
msvc: 0

I think the reason of the difference between gcc and msvc is that compilers optimize unit_val() differently.


Solution

Dynamic initialization of templated non-local variables is always unordered, even relative to other variables defined in the same translation unit (in part because templated variables might also be defined in other translation units). In this simple case, you can avoid the issue by using constant initialization instead: add constexpr to decimal_def::unit_val to enable that, and to the variable template definitions for clarity.



Answered By - Davis Herring
Answer Checked By - Pedro (WPSolving Volunteer)