关于C++ enable_if_t;为什么这段代码不起作用(gcc 8.1,Ubuntu)

About C++ enable_if_t; why is this code not working (gcc 8.1, Ubuntu)

本文关键字:不起作用 代码 gcc Ubuntu 段代码 if enable C++ 为什么 关于      更新时间:2023-10-16
#include <iostream>
#include <type_traits>

struct A {
    template <typename T>
    A(std::enable_if_t<std::is_floating_point<T>::value, T> f) { }
};
int main() {
    std::cout << (std::is_floating_point<double>::value) << std::endl; // true
    A v1((double)2.2);
    return 0;
}

你的T是不可推导的,你可以改用:

struct A {
    template <typename T, std::enable_if_t<std::is_floating_point<T>::value, bool> = false>
    A(T f) { }
};

在构造函数中,T 处于非推导上下文中。它不能从参数中推导出来(并且,对于构造函数,它也不能显式指定)。