SFINAE: are some failures more equal than others?

I am trying to use SFINAE to distinguish a class that has a member called 'name'. I installed things in what seems like a standard template, but it does not work - instead of silently ignoring the "unsuccessful" substitution, the compiler generates an error.

I am sure that I came across some rule of template replacement, I would appreciate if someone could explain which one.

This is a stripped-down example. I am using gcc:

 template <typename U> string test( char(*)[sizeof(U::name)] = 0 ) { return "has name!"; }
 template <typename U> string test(...) { return "no name"; }

 struct HasName { string name; }
 struct NoName  {}

 cout << "HasName: " << test<HasName>(0) << endl;  //fine
 cout << "NoName: " << test<NoName>(0) << endl;    //compiler errors:

 //error: size of array has non-integral type `<type error>'
 //error: `name' is not a member of `NoName'
+5
source share
2 answers

(, , , ):

#include <string>
#include <iostream>
using namespace std;

template <typename U> string test( char(*)[sizeof(U::name)] = 0 ) { return "has name!"; }
template <typename U> string test(...) { return "no name"; }

struct HasName { static string name; };
struct NoName  { };

 int main() {
    cout << "HasName: " << test<HasName>(0) << endl;
    cout << "NoName: " << test<NoName>(0) << endl;
}

:

HasName: has name!
NoName: no name

gcc (GCC) 4.3.4 20090804 () 1

Comeau .

+1

:

// Tested on Microsoft (R) C/C++ Optimizing Compiler Version 15.00.30729.01
template<typename T>
class TypeHasName
{
private:
    typedef char (&YesType)[2];
    typedef char (&NoType)[1];

    struct Base { int name; };
    struct Derived : T, Base { Derived(); };

    template<typename U, U> struct Dummy;

    template<typename U>
    static YesType Test(...);

    template<typename U>
    static NoType Test(Dummy<int Base::*, &U::name>*);

public:
    enum { Value = (sizeof(Test<Derived>(0)) == sizeof(YesType)) };
};

#include <string>  
#include <iostream>  

struct HasName { std::string name; };  
struct NoName {};

int main()
{  
    std::cout << "HasName: " << TypeHasName<HasName>::Value << std::endl;  
    std::cout << "NoName: " << TypeHasName<NoName>::Value << std::endl;  
    return 0;
}

, T name, Derived name ( T Base). T name, Derived Base.

Derived name, &U::name Test() , SFINAE .

0

All Articles