Home > Enterprise >  Is it possible to use a static template variable in a template function?
Is it possible to use a static template variable in a template function?

Time:08-06

For example, in this instance (the code is pretty self-explanatory):

enum types : bool
{
    READ,
    WRITE
};

template<typename T>
auto function(types i, T data)
{
    static T datas;
    if (i == WRITE)
    {
        datas = data;
    }
    else if (i == READ)
    {
        return datas;
    }
}

int main()
{
    function(WRITE, "hello");
    std::cout << function(READ, NULL);
}

The expected output is:

hello

but it ends up in an exception.

Is there any way to fix this or is it not possible?

CodePudding user response:

You should be able to use this kind of logic, but the issue here is that the type parameters for both calls are different.

(There's also another issue of a function with return type T not returning anything, but I'll ignore this for now.)

The first call uses char const* as template parameter and the second one either int or std::nullptr_t depending on how the NULL macro is defined.

Your code results in an uninitialized value being returned by the second call which is undefined behaviour.

You need to make sure the same template parameter is used in both cases:

int main()
{
    function(WRITE, "hello");
    std::cout << function(READ,static_cast<char const*>(nullptr));
}

or

int main()
{
    function(WRITE, "hello");
    std::cout << function<char const*>(READ, nullptr);
}
  • Related