Problem z szablonem funkcji,który zwraca różne typy

0

Kompilator wyrzuca błędy:
main.cpp:4:42: error: no template named 'conditional_t' in namespace 'std'
main.cpp:4:61: error: no member named 'is_floating_point_v' in namespace 'std'
a chodzi konkretnie o szablon funkcji,która ma zwrócić typ zależny od wyniku dodawania dwóch liczb.

#include <iostream>
#include <type_traits>

template <class T,class R,class I = std::conditional_t<std::is_floating_point_v<T>,T,R>>
I sum(T x,R y)
{
    return x+y;
}

int main(int argc, char *argv[])
{
   int a = 20;
   double b = 2.5;

   std::cout<<sum(a,b)<<std::endl;

   return 0;
}
0

Qt 5.14.2 GCC 64bit Debian 10
Piane w Qt Creator

0

Masz składnię z C++17. Jeśli go nie włączyłeś, możesz mieć błędy. Jeśli kompilator nie wspiera Ci tej składni, tak to możesz zrobić:

#include <iostream>
#include <type_traits>

template <class T,class R,class I = typename std::conditional<std::is_floating_point<T>::value,T,R>::type>
I sum(T x,R y)
{
    return x+y;
}

int main(int argc, char *argv[])
{
   int a = 20;
   double b = 2.5;

   std::cout<<sum(a,b)<<std::endl;

   return 0;
}

Osobiście, zastanowił bym się jednak np. nad takim pytaniem: Jeśli mam double i float, to jakim typem wyniku powinno być dodawanie? (IMHO double)
Wtedy lepiej zrobić taką dedukcję:

#include <iostream>
#include <type_traits>

template <class T,class R>
auto sum(T x,R y) -> typename std::enable_if<std::is_floating_point<decltype(x + y)>::value, decltype(x + y)>::type
{
    return x+y;
}

int main(int argc, char *argv[])
{
   int a = 20;
   double b = 2.5;

   std::cout<<sum(a,b)<<std::endl;

   return 0;
}
0

@Quanti994 na debianie jest gcc 6.3. On nie obsługuje pewnych rzeczy z c++17.
Możesz pobrać lub skompilować wersję 7+ wraz z libstdc++7

1 użytkowników online, w tym zalogowanych: 0, gości: 1