Gog*_*ger 4 c++ inheritance templates
以下代码打印:
generic
overload
Run Code Online (Sandbox Code Playgroud)
但我想要的是在两种情况下都调用了重载或特化,而不是通用的.我不是试图将重载与模板专业化混合在一起,因为它们没有像我预期的那样工作.是否有任何模板魔法来实现这一目标?
#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;
}
Run Code Online (Sandbox Code Playgroud)
type_traits
用于测试参数是否派生自Interface的两种方法.
#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>());
}
};
Run Code Online (Sandbox Code Playgroud)
如果满足条件,则禁用模板,仅将非模板作为候选模板.
#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";
}
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2595 次 |
最近记录: |