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

时间:2019-02-05 11:59:24

标签: c++ typetraits

我想调用如下函数模板

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

我认为这里我有一个不可扣除的背景,我该如何更正和

  

可以在此处使用std :: condittional还是使用std :: enable_if?

谢谢。

1 个答案:

答案 0 :(得分:5)

您遇到语法问题,仅此而已:

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();
}