没有专门用于函数指针的函数

Gra*_*rak 2 c++ c++11 c++14 c++17

我正在使用VS2015 Update 3.我有一个函数,我希望根据可调用对象的返回类型进行专门化.当可调用对象是一个仿函数时,一切都按预期工作.当可调用对象是函数或函数指针时,它无法专门化重载函数.我觉得我错过了一些明显的东西,但是我在一年多的时间里没有对SFINAE做过任何事情.

我错过了什么导致专业化失败?

template <typename T>
struct S
{
    T mOp;
    template <typename = void>
    typename std::enable_if<
        std::is_same<
            std::remove_cv_t<
                std::remove_reference_t<
                    decltype(mOp())
                >
            >,
            void
        >::value
    >::type func()
    {
        std::cout << "bool" << std::endl;
    }
    template <typename = void>
    typename std::enable_if<
        std::is_same<
            std::remove_cv_t<
                std::remove_reference_t<
                    decltype(mOp())
                >
            >,
            bool
        >::value
    >::type func()
    {
        std::cout << "void" << std::endl;
    }
};

template <typename T>
auto createS(T&& t)
{
    return S<T>{ t };
}

void vfunc()
{
}
bool bfunc()
{
    return true;
}
struct vfunctor
{
    void operator()()
    {
    }
};
struct bfunctor
{
    bool operator()()
    {
        return true;
    }
};

void func()
{
    createS(bfunc).func();     // Fails to specialize func()
    createS(vfunc).func();     // Fails to specialize func()
    createS(vfunctor{}).func();
    createS(bfunctor{}).func();
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*rry 5

这些都不起作用,因为替换失败只是替换的直接上下文中的失败 - 并且您在不依赖于立即函数模板参数的上下文中尝试SFINAE.您的约束func()基于类模板参数,而不是本地函数模板参数,因此这些只是一个硬错误.

最简单的方法是通过标签调度.包装decltype(mOp())成标签类型然后只是重载:

template <class T> struct tag { };

template <typename T>
struct S
{
    T mOp;

    void func() {
        func_impl(tag<std::decay_t<decltype(mOp())>>{});
    }

    void func_impl(tag<bool> ) { std::cout << "bool\n"; }        
    void func_impl(tag<void> ) { std::cout << "void\n"; }        
};
Run Code Online (Sandbox Code Playgroud)

如果func()由于某种原因你需要对SFINAE友好,那么你可以引入一个新的模板参数来假冒原始模板参数:

template <class..., class U=T>
auto func()
    -> decltype(func_impl(tag<std::decay_t<std::invoke_result_t<U>>>{}))
{
    return func_impl(tag<std::decay_t<std::invoke_result_t<U>>>{});
}
Run Code Online (Sandbox Code Playgroud)

请注意,这必须在各种重载的声明之后出现func_impl.