Zhou.David
Zhou.David

Reputation: 7

template parameters and decltype

codes as follows: '''

template<typename T>
struct has_no_destroy{
    template<typename C>
        
        static char test(decltype(&C::no_destroy));
    
    template<typename C>
        static int32_t test(...);
    
    
    const static bool value = sizeof(test<T>(0)) == 1;
};

struct A{
    
}; 

struct B{
    void no_destroy(){
    }
};

struct C{
    int no_destroy;
    
};

struct D:B{
    
};
void test(){
    std::cout<<has_no_destroy<A>::value<<std::endl;
    std::cout<<has_no_destroy<B>::value<<std::endl;
    std::cout<<has_no_destroy<C>::value<<std::endl;
    std::cout<<has_no_destroy<D>::value<<std::endl;
}

'''

i just want to know why to use test(0) rather than test(1),if i run the first,results ok!but second failed to my expectation! anyone helps?much appreciated!

Upvotes: 1

Views: 60

Answers (1)

songyuanyao
songyuanyao

Reputation: 173044

Because 0 could be interpreted as null pointer, which could be accepted by both the overloaded test. While 1 is an int, which could be accepted only by the 2nd overloaded test, that means value will be always false.

Upvotes: 2

Related Questions