首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SFINAE构造问题

SFINAE构造问题
EN

Stack Overflow用户
提问于 2010-11-08 04:15:06
回答 1查看 126关注 0票数 0

我正在尝试实现is_base模板,我有一个“小问题”。为什么它不工作,因为它被支持?

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-11-08 04:31:45

您显式地为指针提供了一个值:f<Base,Derived>(0, 0),这里不需要进行转换,特别是不需要进行派生到基值的转换;此测试将始终通过,因为第一个测试始终是可调用的(任何指针都可以是空的)。

你想要这样的东西:

代码语言:javascript
复制
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*的指针,如果它实际上是一个派生类,则转换将起作用,并调用第一个重载;否则,调用第二个重载。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4119482

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档