c++ - SFINAE 构造问题

标签 c++ templates

我正在尝试实现 is_base 模板,但遇到“一个小问题”。为什么这不起作用?

#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;
}

最佳答案

您明确地为指针提供了一个值: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* 类型的指针,如果它实际上是一个派生类,转换将起作用并调用第一个重载;否则,第二个。

关于c++ - SFINAE 构造问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4119482/

相关文章:

c++ - 匹配模式作为 Makefile 依赖项中函数的参数

java - 如何制作创建多个文件的 Netbeans 模板?

javascript - JS 替换对象中的占位符值

c++ - cmake find_library 和 CMAKE_FIND_ROOT_PATH

c++ - 具有自定义类型的 qvariant_cast

c++ - 具有 C++11 构造的映射函数

c++ - 私有(private)基类通过子类中的模板友元函数和模板方法影响成员访问

c++ - 关于auto_ptr的一个问题

c++ - 如何更改背景颜色 OnMouseover c++ MFC

c++ - 常量操作数与任何算术运算符的顺序是否会影响优化?