在C ++中编译时间类型确定 [英] Compile time type determination in C++

查看:103
本文介绍了在C ++中编译时间类型确定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同事最近向我展示了一些他在网上找到的代码。它似乎允许编译时确定类型是否具有与另一个类型的is a关系。我认为这是完全真棒,但我必须承认,我没有这个实际工作原理。

A coworker recently showed me some code that he found online. It appears to allow compile time determination of whether a type has an "is a" relationship with another type. I think this is totally awesome, but I have to admit that I'm clueless as to how this actually works. Can anyone explain this to me?

template<typename BaseT, typename DerivedT>
inline bool isRelated(const DerivedT&)
{
    DerivedT derived();
    char test(const BaseT&); // sizeof(test()) == sizeof(char)
    char (&test(...))[2];    // sizeof(test()) == sizeof(char[2])
    struct conversion 
    { 
        enum { exists = (sizeof(test(derived())) == sizeof(char)) }; 
    };
    return conversion::exists;
} 


$ b >

Once this function is defined, you can use it like this:

#include <iostream>

class base {};
class derived : public base {};
class unrelated {};

int main()
{
    base b;
    derived d;
    unrelated u;

    if( isRelated<base>( b ) )
        std::cout << "b is related to base" << std::endl;

    if( isRelated<base>( d ) )
        std::cout << "d is related to base" << std::endl;

    if( !isRelated<base>( u ) )
        std::cout << "u is not related to base" << std::endl;
} 


推荐答案

它声明两个重载的函数 test ,一个采用 Base ,一个采取任何 c $ c>,并返回不同的类型。

It declares two overloaded functions named test, one taking a Base and one taking anything (...), and returning different types.

然后调用 Derived 的返回类型来查看调用了哪个重载。 (它实际上调用函数的返回值返回 Derived ,以避免使用内存)

It then calls the function with a Derived and checks the size of its return type to see which overload is called. (It actually calls the function with the return value of a function that returns Derived, to avoid using memory)

因为 enum 是编译时常量,所有这些都是在编译时在类型系统中完成的。由于函数不会在运行时被调用,因此它们没有主体没有关系。

Because enums are compile-time constants, all of this is done within the type system at compile-time. Since the functions don't end up getting called at runtime, it doesn't matter that they have no bodies.

这篇关于在C ++中编译时间类型确定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆