无法使用 std::conditional 推导模板参数类型

Can't deduct template parameter type using std::conditional

我想调用如下函数模板

#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
}

我认为这里有一个不可扣除的上下文,我该如何更正它

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

谢谢。

你遇到了语法问题,没有别的:

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

正如 Jarod42 在评论中指出的那样,这允许用户绕过您的意图并对第二个参数做任何事情。您可以改用 typedef:

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