boost :: enable_if类模板方法

Any*_*orn 9 c++ templates boost sfinae

我得到了一个模板方法类,看看这个:

struct undefined {};

template<typename T> struct is_undefined : mpl::false_ {};

template<> struct is_undefined<undefined> : mpl::true_ {};

template<class C>
struct foo {
        template<class F, class V>
        typename boost::disable_if<is_undefined<C> >::type
            apply(const F &f, const V &variables) {
        }

        template<class F, class V>
        typename boost::enable_if<is_undefined<C> >::type
            apply(const F &f, const V &variables) {
        }
};
Run Code Online (Sandbox Code Playgroud)

显然,两个模板都被实例化,导致编译时错误.是否实例化模板方法不同于自由函数的实例化?我已经解决了这个问题,但我想知道是什么.我唯一能想到的可能会导致这种行为,启用条件不依赖于立即模板参数,而是依赖于类模板参数

谢谢

Joh*_*itb 12

C没有参加扣除apply.请参阅此答案,以深入解释代码失败的原因.

你可以像这样解决它:

template<class C>
struct foo {    
        template<class F, class V>
        void apply(const F &f, const V &variables) { 
            apply<F, V, C>(f, variables); 
        }

private:
        template<class F, class V, class C1>
        typename boost::disable_if<is_undefined<C1> >::type
            apply(const F &f, const V &variables) {
        }

        template<class F, class V, class C1>
        typename boost::enable_if<is_undefined<C1> >::type
            apply(const F &f, const V &variables) {
        }
};
Run Code Online (Sandbox Code Playgroud)