c++ - 是否可以在模板特化中匹配模板化基础?

标签 c++ templates metaprogramming

如果基类不是模板,我当然可以使用 is_base。但是,当它是时,我只是看不到任何方法来一般匹配任何派生类型。这是我的意思的一个基本示例:

#include <boost/mpl/bool.hpp>

template < typename T >
struct test_base
{
};

template < typename T >
struct check : boost::mpl::false_ {};

template < typename T >
struct check<test_base<T> > : boost::mpl::true_ {};

struct test_derived : test_base<int> {};

#include <iostream>
int main() 
{
  std::cout << check<test_derived>::value << std::endl;
  std::cin.get();
}

我希望它返回 true_ 而不是 false_。真实的例子有大约 7 个模板参数,大多数是默认的,并使用 Boost.Parameter 按名称引用它们。为了使用 is_base,我必须能够以某种方式提取参数,但除了声明内部 typedef 之外,我看不出有什么方法可以做到这一点。

我认为这是不可能的。希望被证明是错误的。

最佳答案

你只需要稍微调整一下你的测试:

#include <iostream>
#include <boost/mpl/bool.hpp>

template < typename T >
struct test_base
{
};

template < typename T >
struct check_
{
    template<class U>
    static char(&do_test(test_base<U>*))[2];
    static char(&do_test(...))[1];
    enum { value = 2 == sizeof do_test(static_cast<T*>(0)) };
};

template < typename T >
struct check : boost::mpl::bool_<check_<T>::value> {};

struct test_derived : test_base<int> {};

int main()
{
  std::cout << check<test_derived>::value << std::endl;
}

关于c++ - 是否可以在模板特化中匹配模板化基础?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3407852/

相关文章:

c++ - 混合运行时/编译时条件下的标签调度

c++ - 为什么专用模板类需要前向声明?

c++ - 为什么模板参数中不允许类类型对象?

c++ - 更改给定 STL 容器的 value_type

c++ - 模板类根据它们的存在和优先级调用其他类的一些命名函数

c++ - 动态调用 Openh264 函数导致我的应用程序崩溃

c++ - EnableWindow(hWnd, false) 不禁用键盘输入

c++ - 在QML中访问C++对象的成员变量

c++ - 如何为枚举创建模板运算符

c++ - 在模板特化中模拟开关组件