【问题标题】:change function defination based on type trait? [duplicate]根据类型特征更改函数定义? [复制]
【发布时间】:2020-06-09 17:28:17
【问题描述】:

我想使用enable_if_t 根据类型更改我的函数定义。类似这样的东西:

#include<type_traits>
template<typename T> struct A;

template<typename T>
struct A{
    std::enable_if_t<std::is_arithmetic<T>::value, bool>
    test()
    {
        return true;
    }
    std::enable_if_t<!std::is_arithmetic<T>::value,  bool>
    test()
    {
        return false;    
    }

};

目前it cannot compile at all

【问题讨论】:

  • 不允许具有相同名称和签名的类方法。函数的返回类型不是其签名的一部分。这里最简单的解决方案是将返回类型声明为auto,并使用if constexpr返回适当的类型。

标签: c++ c++17 sfinae typetraits


【解决方案1】:

你可以试试

template <typename U = T>
std::enable_if_t<std::is_arithmetic<U>::value, bool>
test()
 { return true; }

template <typename U = T>
std::enable_if_t<!std::is_arithmetic<U>::value,  bool>
test()
 { return false; }

我的意思是... SFINAE 处理函数/方法的模板参数,而不是包含方法的类的模板参数。

使用typename U = T,您可以将类模板参数T 转换为方法模板参数U

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    • 2018-05-08
    • 2021-05-08
    • 2014-10-07
    • 1970-01-01
    相关资源
    最近更新 更多