C++ SFINAE enable_if_t 在成员函数中,如何消除歧义?

标签 c++ c++11 templates sfinae enable-if

假设我们有一些 SFINAE 成员函数:

class foo{
    template <class S, class = std::enable_if_t<std::is_integral<S>::value, S>
    void bar(S&& s);
    template <class S, class = std::enable_if_t<!std::is_integral<S>::value, S>
    void bar(S&& s);
}

如果我们像上面那样声明,那么我们如何定义它们呢?他们的两个函数签名看起来像:

template <class S, class>
inline void foo::bar(S&& s){ ... do something ... }

我见过返回 std::enable_if_t<...> 的示例喜欢:

template <class S, class>
auto bar(S&& s) -> std::enable_if_t<!std::is_integral<S>::value, S>(...){
    ... do something ...
}

根据返回类型消除歧义。但我不想退还任何东西。

最佳答案

因为默认参数不是函数签名的一部分,所以让它们不是默认值

class foo{
    template <class S, typename std::enable_if<std::is_integral<S>::value, int>::type = 0>
    void bar(S&& s);
    template <class S, typename std::enable_if<!std::is_integral<S>::value, int>::type = 0>
    void bar(S&& s);
};

Live Demo


编辑:应大众需求,这是 C++17 中的相同代码:

class foo{
public:
    template <class S>
    void bar(S&& s)
    {
        if constexpr(std::is_integral_v<S>)
            std::cout << "is integral\n";
        else
            std::cout << "NOT integral\n";
    }
};

constexpr if 语句对编译器来说是特殊的,因为分支是在编译时选择的,而未采用的分支甚至没有实例化

C++17 Demo

关于C++ SFINAE enable_if_t 在成员函数中,如何消除歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52083873/

相关文章:

c++ - OpenCV 使用像素指针构建图像

c++ - 执行 cin 后计算标准输入中的字符数

c++ - 使文件只对程序可读

templates - EmberJS 多产量助手

C++:模板参数循环依赖

c++ - 如何让 Visual Studio 将所有文件保存为 UTF-8 而无需在项目或解决方案级别签名?

c++ - 如何修复对 strstr 没有匹配的函数调用

c++11 - Rcpp:以对象作为参数调用函数

c++ - 从 map 中检索后 map 中的对象损坏

c++ - 不重写类的部分模板特化