2010-11-07 4 views
0

Я пытаюсь реализовать шаблон is_base, и у меня есть «небольшая проблема». Почему это не работает, поскольку это suppouse?Проблема с строкой SFINAE

#include <iostream> 
using std::cout; 
class Car 
{ 
}; 

class Fiesta : public Car 
{ 
}; 

template<class Base, class Derived> 
struct isBase 
{ 
    typedef char yes[2]; 
    typedef char no[1]; 

    template<class B, class D> 
    static yes& f(D* d, B* b = d); 

    template<class,class> 
    static no& f(...); 

    static bool type; 
}; 




template<class Base, class Derived> 
bool isBase<Base,Derived>::type = (sizeof(f<Base,Derived>(0,0)) == sizeof(yes)); 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    cout << isBase<Fiesta,Car>::type;//It should say false here but says true 

    return 0; 
} 

ответ

2

Вы явно указав значение для указателя: f<Base,Derived>(0, 0), преобразование не должно произойти здесь, особенно не производный к базе одного; этот тест всегда будет проходить, поскольку первый из них всегда вызывается (любой указатель может быть нулевым).

Вы хотите что-то вроде этого:

template<class Base, class Derived> 
struct isBase 
{ 
    typedef char yes[2]; 
    typedef char no[1]; 

    template <class B> 
    static yes& f(B*); 

    template <class> 
    static no& f(...); 

    // (1) make it const (as it should be) and just define it inline 
    // (2) it's not a type, it's a value; name appropriately 
    static const bool value = sizeof(f<Base>((Derived*)0)) == sizeof(yes); 
}; 

// use a standard signature for main 
int main() // if you don't need the arguments, don't list them 
{ 
    cout << isBase<Fiesta, Car>::value; 
    cout << isBase<Car, Fiesta>::value; 

    // return 0 is implicit for main, helpful for snippets 
} 

Первая перегрузка будет вызвана, если тип указателя или может быть преобразован в Base*. Поэтому мы делаем указатель типа Derived*, и если он фактически является производным классом, преобразование будет работать и вызывается первая перегрузка; в противном случае - второй.

+0

отлично, я знал, что я испортил что-то с моим первым fnc. Благодарю. –

+0

и спасибо за ваши советы и исправления –

Смежные вопросы