Art*_*yom 5 c++ inheritance template-specialization
我有以下场景:
class my_base { ... }
class my_derived : public my_base { ... };
template<typename X>
struct my_traits;
Run Code Online (Sandbox Code Playgroud)
我想专门my_traits用于从my_base包括派生的所有类,例如:
template<typename Y> // Y is derived form my_base.
struct my_traits { ... };
Run Code Online (Sandbox Code Playgroud)
我在添加标签、成员my_base以使其更简单方面没有问题。我已经看到了一些技巧,但我仍然感到迷茫。
如何以简单而简短的方式做到这一点?
好吧,您不需要编写自己的 isbaseof。您可以使用 boost 或 c++0x。
#include <boost/utility/enable_if.hpp>
struct base {};
struct derived : base {};
template < typename T, typename Enable = void >
struct traits;
template < typename T >
struct traits< T, typename boost::enable_if<std::is_base_of<base, T>>::type >
{
enum { value = 5 };
};
#include <iostream>
int main()
{
std::cout << traits<derived>::value << std::endl;
std::cin.get();
}
Run Code Online (Sandbox Code Playgroud)
存在扩展问题,但我不认为它们比其他问题中的替代方案更好或更差。