Fab D'
Fab D'

Reputation: 5

How do I get the template function type when passing a std::vector<T>?

I'm trying to implement a templated function that takes as argument either a std::vector<float>& or a std::vector<std::vector<float>>. Below a simplified version of my code.

I'm getting errors like:

C2440 'initializing' cannot convert from initializer list

when I tried to implement this when calling function PlotDataset().

What is the best/cleanest way to achieve this?

template<typename T>
plot(T& y)
{
    // depending on whether T is a float or a std::vector<float>,
    // I want to set my for loop differently
    if(std::is_same<T, std::vector<std::vector<float>>>::value)
    {
        for(size_t n{0}; n < y.size(); n++)
        {
            // axes is a shared_ptr, while PlotDataset is a class constructor
            // taking a std::vector<float> as argument
            axes->addDataset(PlotDataset(y.at(n)));
        }
    }
    else if(std::is_same<T, std::vector<float>>::value)
    {
            axes->addDataset(PlotDataset(y))
    }
}

Upvotes: 0

Views: 65

Answers (1)

Lukas-T
Lukas-T

Reputation: 11370

Here you will have to use if constexpr

if constexpr (std::is_same<T, std::vector<std::vector<float>>>::value)
{
    ...
}
else if constexpr (std::is_same<T, std::vector<float>>::value)
{
       ...
}

But now you have a function template that works only for 2 very specific types and doesn't do anything for any other type. I think in this case it would be much better (easier to use, clearer interface, less overhead from if constexpr) to use an overloaded function:

plot(std::vector<std::vector<float>> &y) 
{
    for(size_t n{0}; n < y.size(); n++)
    {
        axes->addDataset(PlotDataset(y.at(n)));
    }
}

plot(std::vector<float> &y)
{
    axes->addDataset(PlotDataset(y))
}

If you want to support datatypes other than float you could still make these templates.

Upvotes: 3

Related Questions