【问题标题】:Is it possible to match templated base in template specializations?是否可以在模板专业化中匹配模板化基础?
【发布时间】:2010-08-04 16:55:31
【问题描述】:

如果基类不是模板,我当然可以使用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,我必须能够以某种方式提取参数,而且除了声明内部类型定义之外,我没有办法做到这一点。

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

【问题讨论】:

  • 你能在测试库中引入独特的标签类型并根据它禁用/启用吗?
  • 这是一个可行的选择,我应该自己考虑。不过,如果有人能在没有它的情况下找到解决方法,仍然很感兴趣。
  • @aaa - 你应该这样回答。有一种感觉,这是唯一可能的方法,所以在我没有得到答复后的几天内,您不妨为此获得荣誉。
  • 也许我会等几天,有经验的人可能正在寻找未回答的问题?

标签: c++ templates metaprogramming


【解决方案1】:

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

#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;
}

【讨论】:

  • 太棒了! SFINAE 再次进行救援。
  • 这里不涉及SFINAE,只是纯粹的函数重载。 IE。实例化 do_test(test_base*) 永远不会产生错误。
猜你喜欢
  • 1970-01-01
  • 2020-07-18
  • 2020-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
相关资源
最近更新 更多