所有子类的c ++模板专业化 [英] c++ template specialization for all subclasses

查看:149
本文介绍了所有子类的c ++模板专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个这样的模板函数:

I need to create a template function like this:

template<typename T>
void foo(T a)
{
   if (T is a subclass of class Bar)
      do this
   else
      do something else
}

我也可以想象使用模板专门化...但我从来没有见过一个模板超类的所有子类的专业化。我不想为每个子类重复专门化代码

I can also imagine doing it using template specialization ... but I have never seen a template specialization for all subclasses of a superclass. I don't want to repeat specialization code for each subclass

推荐答案

你可以做你想要的,但不是你想如何做吧!您可以使用 std :: enable_if std :: is_base_of

You can do what you want but not how you are trying to do it! You can use std::enable_if together with std::is_base_of:

#include <iostream>
#include <utility>
#include <type_traits>

struct Bar { virtual ~Bar() {} };
struct Foo: Bar {};
struct Faz {};

template <typename T>
typename std::enable_if<std::is_base_of<Bar, T>::value>::type
foo(char const* type, T) {
    std::cout << type << " is derived from Bar\n";
}
template <typename T>
typename std::enable_if<!std::is_base_of<Bar, T>::value>::type
foo(char const* type, T) {
    std::cout << type << " is NOT derived from Bar\n";
}

int main()
{
    foo("Foo", Foo());
    foo("Faz", Faz());
}

由于这些东西变得更广泛,人们讨论了某种 static if 但是到目前为止还没有出现。

Since this stuff gets more wide-spread, people have discussed having some sort of static if but so far it hasn't come into existance.

两者 std: :enable_if std :: is_base_of (在< type_traits> 中声明)在C ++ 2011。如果您需要使用C ++ 2003编译器进行编译,您可以从 Boost 使用它们的实现(您需要将命名空间更改为 boost 并包括boost / utility.hppboost / enable_if.hpp,而不是相应的标准头文件)。或者,如果你不能使用Boost,这两个类模板都可以很容易实现。

Both std::enable_if and std::is_base_of (declared in <type_traits>) are new in C++2011. If you need to compile with a C++2003 compiler you can either use their implementation from Boost (you need to change the namespace to boost and include "boost/utility.hpp" and "boost/enable_if.hpp" instead of the respective standard headers). Alternatively, if you can't use Boost, both of these class template can be implemented quite easily.

这篇关于所有子类的c ++模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆