打印以下代码:
generic
overload
但我想要的是在这两种情况下都调用重载或专业化,而不是通用的。我并不是想将重载与模板专业化混合在一起,它们在一起是因为没有一个按我的预期工作。有什么模板魔法可以实现这一点吗?
#include <iostream>
class Interface {};
class Impl: public Interface {};
class Bar
{
public:
template<typename T> void foo(T& t) {
std::cout << "generic\n";
}
void foo(Interface& t) {
std::cout << "overload\n";
}
};
template<> void Bar::foo<Interface>(Interface& t) {
std::cout << "specialization\n";
}
int main() {
Bar bar;
Impl impl;
Interface& interface = impl;
bar.foo(impl);
bar.foo(interface);
return 0;
}
两种使用方式type_traits
测试参数是否源自接口。
#include <boost/type_traits.hpp>
class Interface {};
class Impl: public Interface {};
class Bar
{
template <class T> void foo_impl(T& value, boost::false_type)
{
std::cout << "generic\n";
}
void foo_impl(Interface& value, boost::true_type)
{
std::cout << "Interface\n";
}
public:
template<typename T> void foo(T& t) {
foo_impl(t, boost::is_base_of<Interface, T>());
}
};
或者,如果满足条件,则禁用模板,仅保留非模板作为候选。
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits.hpp>
class Interface {};
class Impl: public Interface {};
class Bar
{
public:
template<typename T>
typename boost::disable_if<boost::is_base_of<Interface, T>, void>::type foo(T& t)
{
std::cout << "generic\n";
}
void foo(Interface&)
{
std::cout << "Interface\n";
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)