简体   繁体   中英

enable_if on member template function of class template

This seams to be a bug in MSVC10?

#include <type_traits>

template<int j>
struct A{
    template<int i>
    typename std::enable_if<i==j>::type
        t(){}
};

int main(){
    A<1>().t<1>();  //error C2770
}

error C2770: invalid explicit template_or_generic argument(s) "enable_if::type A::t(void)".

The following compiles:

#include <type_traits>

template<class j>
struct A{
    template<class i>
    typename std::enable_if<std::is_same<i,j>::value>::type
        t(){}
};

template<unsigned int j>
struct B{
    template<unsigned int i>
    typename std::enable_if<i==j>::type
        t(){}
};

int main(){
    A<int>().t<int>();
    B<1>().t<1>();
}

This appears to be some strange behaviour on the part of MSVC2010 where it is unable to make a determination as to whether your use of <1> as a template parameter is an instantiation of an int-based template.

When I compile your code above, I get the following, verbose error:

    error C2770: invalid explicit template argument(s) for 
    'std::enable_if<i==1>::type A<j>::t(void)'
    with
    [
        j=1
    ]
    d:\programming\stackoverflow\stackoverflow\stackoverflow.cpp(11) : 
    see declaration of 'A<j>::t'
    with
    [
        j=1
    ]

If you swap your 1 values out for 0, you find it still doesn't work, but if you use any other valid int, the template appears to compile quite happily.

I'm not entirely sure why this is happening, but you can make this code work by using const ints to represent the template parameters:

    template<int j>
    struct A{
        template<int i>
        typename std::enable_if<i == j>::type
            t(){}
    };

    int main(){

        const int j = 1;
        const int i = 1;

        A<j>().t<i>();   //now compiles fine
    }

My suspicion, based on this, is that the compiler finds the use of 0 and 1 ambiguous when it comes to template instantiation. Hopefully the workaround here is helpful to someone stumbling across this through google...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM