Sklert
Sklert

Reputation: 242

Type depends on condition in template

Can I make a template function with arguments, which types are depends on template argument? (Code below is just to explain, what I want)

#include <complex>

template <bool two>
void foo( (if (two) ? double* : std::complex<double>* >) input, size_t n)
{
    for (size_t i = 0; i < n; ++n)
        input[i] *= two ? 2.0 : 1.0;
}

void foo_double(double *input, size_t n){
    foo<true>(input,n);

}

void foo_complex (std::complex<double> *input, size_t n){
    foo<false>(input,n);
} 

I thought std::conditional would help, but I guess, I don't know how to use it correctly here (code below can't be compiled)

#include <type_traits>
#include <complex>

template <bool two>
void foo(std::conditional<two, double*, std::complex<double>* > input, size_t n)
{
    for (size_t i = 0; i < n; ++n)
        input[i] *= two ? 2.0 : 1.0;
}

void foo_double(double *input, size_t n){
    foo<true>(input,n);

}

void foo_complex (std::complex<double> *input, size_t n){
    foo<false>(input,n);
}

It would be very nice, if someone find solution without higher than c++11, so I will be able to compile it both in vs2012 and with gcc-6+. But some examples with c++14 or higher will be good experience too.

Thanks =)

Upvotes: 0

Views: 214

Answers (1)

max66
max66

Reputation: 66230

You only have to add a ::type and a typename

template <bool two>
// ......*typename*.....................................................*::type*
void foo (typename std::conditional<two, double*, std::complex<double>* >::type input, size_t n)
{
    for (size_t i = 0; i < n; ++n)
        input[i] *= two ? 2.0 : 1.0;
}

Upvotes: 2

Related Questions