混合模板函数的重载和继承 [英] Mixing template function overloading and inheritance

查看:74
本文介绍了混合模板函数的重载和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码打印:

generic
overload

但是我想要的是在这两种情况下都调用了重载或专业化,而不是通用的.我不是在尝试将重载与模板专业化混为一谈,因为它们没有按我的预期工作,所以它们在一起.是否有任何模板魔术可以完成此任务?

But what I wanted is that the overload or the specialization were called in both cases, not the generic one. I'm not trying to mix overloading with template specialization, they're here together because none worked as I expected. Is there any template magic to accomplish this?

#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来测试参数是否从Interface派生的两种方法.

Two ways using type_traits to test if the argument is derived from 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>());
    }

};

或在满足条件的情况下禁用模板,仅将非模板作为候选.

Or disable the template if the condition is met, leaving only the non-template as a candidate.

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

这篇关于混合模板函数的重载和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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