2

I have a function template where the return type of the function is the template argument. According to https://en.cppreference.com/w/cpp/language/template_argument_deduction, we can have a template argument deduction with the following examples

template<typename To, typename From>
To convert(From f);

Now as an example, I want to make a specialized function for this where I passed the following:

auto x = convert<std::array>(6000); // the From should be deduced as int.

In this case, I want to make a specialized function template, where the sizeof the From determines the size of the array , and to keep it simple, assume that uint8_t is the type of the array as the data type which represents 1 byte.

Therefore, the type of x should be std::array<uint8_t, 4>.

Another example:

auto y = convert<std::array>(1.02322); // the From should be deduced as double

In this case, the type of y should be std::array<uint8_t, 8>.

The second problem is if std::vector is passed as a template argument

auto x = convert<std::vector>(6000); // the From should be deduced as int

The type of x should be std::vector<uint8_t>, and the length of the vector is 4

How to make such function template that can accept both std::array and std::vector, and without using any std::span algorithm as I am limited to c++11/14

0

1 Answer 1

3

std::array and std::vector are different kinds of template.

To match std::vector, you can have

template <template <typename...> class To, typename From>
To<uint8_t> convert(From from);

To match std::array, you need

template <template <typename, std::size_t> class To, typename From>
To<uint8_t, sizeof(From)> convert(From from);

But this is good, because you can't partially specialise a function template. Here you instead have overloads.

See it on coliru

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.