【问题标题】:SFINAE did not compile [duplicate]SFINAE没有编译[重复]
【发布时间】:2015-07-21 12:29:42
【问题描述】:

我以前经常使用 SFINAE,但我有一个非常简单的示例,我今天无法运行。

class X
{
    public:
        template <typename CHECK, typename = typename std::enable_if< std::is_floating_point<CHECK>::value, void>::type >
            void Do()
            {
                std::cout << "yes" << std::endl;
            }

        template <typename CHECK, typename = typename std::enable_if< !std::is_floating_point<CHECK>::value, void>::type>
            void Do()
            {
                std::cout<< "no" << std::endl;
            }

};

int main()
{
    X x;
    x.Do<float>();
}

错误:

src/main.cpp:20:18: 错误:'template void X::Do()' 不能重载

src/main.cpp:14:18: 错误: with 'template void X::Do()' 无效的 Do()

我想用 enable_if 禁用任何过载,但它不起作用...

知道我今天做错了什么吗?

【问题讨论】:

    标签: c++11 sfinae enable-if


    【解决方案1】:

    这两个函数具有相同的签名,因此会出现重新定义错误。试试下面的,它使用默认参数:

    #include <type_traits> 
    #include <iostream>
    
    class X
    {
        public:
            template <typename CHECK, std::enable_if_t< std::is_floating_point<CHECK>::value>* =nullptr >
                void Do()
                {
                    std::cout << "yes" << std::endl;
                }
    
            template <typename CHECK, std::enable_if_t< !std::is_floating_point<CHECK>::value>* =nullptr>
                void Do()
                {
                    std::cout<< "no" << std::endl;
                }
    
    };
    
    int main()
    {
        X x;
        x.Do<float>();
    }
    

    DEMO

    另请参阅答案herehere

    【讨论】:

    • 谢谢。但是我对 enable_if 的工作原理有很大的误解。如果条件为假,我认为 enable_if 会导致“编译错误”,因此模板将被“禁用”,因此我只有一个不能重载的实例。但是现在我超负荷了,SFINAE 似乎不起作用。你能解释一下吗?
    【解决方案2】:

    另一种编译和工作的语法是将enable_is 作为返回类型:

    class X
    {
    public:
        template <typename CHECK >
        typename std::enable_if< std::is_floating_point<CHECK>::value, void>::type Do()
        {
            std::cout << "yes" << std::endl;
        }
    
        template <typename CHECK>
        typename std::enable_if< !std::is_floating_point<CHECK>::value, void>::type Do()
        {
            std::cout << "no" << std::endl;
        }
    
    };
    
    int main()
    {
        X x;
        x.Do<float>();
        getchar();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多