c++ - 如何确定一个模板参数可以转换成算术类型?

标签 c++ c++11 templates c++14 sfinae

我想要这样的东西:

template<typename T, typename = void> // sth like T=>int or T=>double not valid
struct test : std::false_type{};

template<typename T, ???> // what should i do?
struct test<T,???> : std::true_type{};

这将导致:

std::cout << test<int>::value << std::endl;

将返回“true”和一个自定义类

class a{ int a;double b};
std::cout << test<a>::value << std::endl;

会返回“假”

最佳答案

总有一个完全显式的测试可以用于隐式转换

namespace detail
{
    std::true_type check(int);
    std::true_type check(float);
    std::true_type check(char);
    // ...
    std::false_type check(...);
}

template<typename T>
struct is_implicitly_convertible_to_arithmetic
    : decltype(::detail::check(std::declval<T>())) {};

这很冗长,但非常灵活。

关于c++ - 如何确定一个模板参数可以转换成算术类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49995195/

相关文章:

c++ - 检查到目前为止我在 C++ 中使用了哪些值的最快方法是什么?

二级层次类 : do not understand why it does not work 中的 C++ 多态性

c++ - 如果对象是右值,确保成员变量被移动

delphi - Delphi 中泛型类型的算术运算

c++ - 为什么与 EBO 无关的 VBO 中的数据也被提供给 OpenGL?

android - char*转wchar_t*时如何设置Locale?

c++ - Ratio<,> 是常量,但如果我想接受不同的比率作为参数怎么办?

C++ 将数组的所有值写入txt文件

c++ - 从 Class<U> 调用 Class<T> 的私有(private)构造函数

python - Django 模板的 Axure 输出