1

I would like to call a function template like below

#include <iostream>
#include <type_traits>
#include <typeinfo>
using namespace std;

struct size1 { size1() {std::cout << "Caling 1 \n";}};
struct size2 { size2() {std::cout << "Caling 2 \n";}};

template <typename T, typename std::conditional_t<sizeof(T) == 4, size1, size2> U>
void afficher(T a)
{
    std::cout << typeid(U).name();
}


int main(int argc, char *argv[])
{
    afficher(10); //Error can't deduct U
}

I think that here I have a non-deductable context, how could I correct it and

is it ok to user std::condittional here or use std::enable_if ?

Thank you.

Blood-HaZaRd
  • 2,049
  • 2
  • 20
  • 43
  • 1
    About [using namespace std](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)... – Aconcagua Feb 05 '19 at 12:00
  • `std::enable_if` does not do the same; you'd have to provide two overloads then (keyword SFINAE). – Aconcagua Feb 05 '19 at 12:04

1 Answers1

5

You've got a syntax problem, nothing else:

template <typename T, typename U = std::conditional_t<sizeof(T) == 4, size1, size2>>
void afficher(T a)         //  ^^^^
{
    std::cout << typeid(U).name();
}

As noted by Jarod42 in the comments, this allows users to bypass your intent and do whatever with the second argument. You could use a typedef instead:

template <typename T>
void afficher(T a)
{
    using U = std::conditional_t<sizeof(T) == 4, size1, size2>>;
    std::cout << typeid(U).name();
}
jrok
  • 54,456
  • 9
  • 109
  • 141
  • 1
    @Jarod42 That is true. You can break lots of stuff if you try hard enough :) – jrok Feb 05 '19 at 12:11
  • `template void afficher(T a) { using U = std::conditional_t; std::cout << typeid(U).name(); }` would avoid that issue. – Jarod42 Feb 05 '19 at 12:13
  • @jrok thank you and for the note provided by Jarod. But is there a way to get the second paramter deduced outside the function's body scope ? – Blood-HaZaRd Feb 05 '19 at 12:29