gpt4 book ai didi

c++ - std::enable_if,模板特化和继承

转载 作者:太空狗 更新时间:2023-10-29 21:05:29 27 4
gpt4 key购买 nike

我想问你一些关于这段代码的建议。它有效,但我认为它可以用更优雅的方式编写。这是一段 C++11 代码,因此在编译它时请牢记它;)!

#include <iostream>
#include <type_traits>
#include <typeinfo>

using namespace std;

class A {};
class B: public A {};

class C {};
class D: public C {};

class E: public A, public C {};

template<class T, typename = void>
class Example;

template<class T>
class Example<T, typename enable_if<is_base_of<A, T>::value and not is_base_of<C, T>::value>::type>
{
public:
string a() const
{
return string(typeid(T).name()) + " have A as base class";
}
};

template<class T>
class Example<T, typename enable_if<not is_base_of<A, T>::value and is_base_of<C, T>::value>::type>
{
public:
string b() const
{
return string(typeid(T).name()) + " have C as base class";
}
};

template<class T>
class Example<T, typename enable_if<is_base_of<A, T>::value and is_base_of<C, T>::value>::type> :
public Example<A>,
public Example<C>
{
};

int
main()
{
Example<B> example1;
Example<D> example2;
Example<E> example3;

cout << example1.a() << endl;
//cout << example1.b() << endl; It must raise a compile error
//cout << example2.a() << endl; It must raise a compile error
cout << example2.b() << endl;
cout << example3.a() << endl;
cout << example3.b() << endl;
}

如您所见,我正在尝试编写一个类模板,它可以处理从 AC 派生的类。问题是当 AC 被继承为类 E 时。事实上,我们也可以有这样的东西......

template<class T>
class Example<T, typename enable_if<is_base_of<A, T>::value> { /* ... */ };

template<class T>
class Example<T, typename enable_if<is_base_of<C, T>::value> { /* ... */ };

...但是当类(如 E)继承 AC 时它将失败。

关于更好的代码有什么想法吗?谢谢

最佳答案

更简单的方法是使用 static_assert

template <typename T>
class Example
{
public:
std::string a() const
{
static_assert(std::is_base_of<A, T>::value, "T must derive from A to use a()");
return std::string(typeid(T).name()) + " have A as base class";
}

std::string b() const
{
static_assert(std::is_base_of<C, T>::value, "T must derive from C to use b()");
return std::string(typeid(T).name()) + " have C as base class";
}
};

关于c++ - std::enable_if,模板特化和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9797325/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com