0

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?

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.