Reputation: 2124
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.
Upvotes: 1
Views: 78
Reputation: 55395
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();
}
Upvotes: 5