我需要创建一个像这样的模板函数:
template<typename T>
void foo(T a)
{
if (T is a subclass of class Bar)
do this
else
do something else
}
我也可以想象使用模板专业化来做到这一点......但我从未见过针对超类的所有子类的模板专业化。我不想为每个子类重复专门化代码
你可以做你想做的事,但不能做你想做的事!您可以使用std::enable_if
和...一起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
但到目前为止它还没有出现。
Both std::enable_if
and std::is_base_of
(声明于<type_traits>
) 是 C++2011 中的新增内容。如果您需要使用 C++2003 编译器进行编译,您可以使用它们的实现Boost(您需要将命名空间更改为boost
并包括"boost/utility.hpp"
and "boost/enable_if.hpp"
而不是相应的标准标题)。或者,如果您不能使用 Boost,这两个类模板都可以很容易地实现。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)