c++ - 使用模板化基础编译时间类选择器

标签 c++ templates

给定以下代码序列:

#include <iostream>

using namespace std;

template <typename T>
class Base
{
    public:
        T* t;
        void b() {}
};

class D1:
        public Base<D1>
{
    public:
        int d1;
};

class D2:
        public D1
{
    public:
        int d2;
};

template <typename T>
class Selector
{
    public:

        template <typename U>
        void a(Base<U>& base)
        {
            cout << __LINE__ << endl;
            base.b();
        }

        template <typename U>
        void a(U& u)
        {
            cout << __LINE__ << endl;
        }
};


int main()
{
    D2 derivated;
    Selector<D2> s;
    s.a(derivated);
    return 0;
}

我想检查某些类 (D2) 是否有基类 (Base) 继承了任何 D2 父类。 我只是无法让 Selector 命中最专业的成员函数。

最佳答案

您可以设置自己的特征来检查类型是否有任何 Base<T>作为祖先。以下对我有用:

template <typename T> struct Foo { };

struct Bar : Foo<Bar> { };

struct Zip : Bar { };

#include <type_traits>

template <typename T>
class derives_from_any_foo
{
    typedef char yes;
    typedef char no[2];

    template <typename U>
    static yes & test(Foo<U> const &);

    static no & test(...);

public:
    static bool const value = sizeof(test(std::declval<T>())) == sizeof(yes);
};

#include <iostream>

int main()
{
    std::cout << "int: " <<  derives_from_any_foo<int>::value << "\n"
              << "Bar: " <<  derives_from_any_foo<Bar>::value << "\n"
              << "Zip: " <<  derives_from_any_foo<Zip>::value << "\n";
}

通常不需要任何对象实例来进行这些类型检查;一切都是静态的。如果您有对象,请使用 decltype获取其类型,或添加类型推导辅助函数。

关于c++ - 使用模板化基础编译时间类选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13233400/

相关文章:

C++ vector 插入新对象

c++ - is_trivially_destructible : invalid use of incomplete type ‘class Bar2’

c++ - 奇怪的 "undefined reference"模板成员

c++ - 高级 C++ : Copy configuration (object) in a template template class's instance

c++ - 如何获取模板模板参数的模板参数?

javascript - 如何在 mustache.js 中完成 if/else?

c++ - 复杂的错误处理

c++ - 隐式常量转换溢出 [-Werror=overflow]

c++ - 类型推导失败 : shared_ptr of derived template to base template as function argument

c++ - 返回嵌套类的对象