【问题标题】:C++ Is there a way to have template overload based on type_traits?C++ 有没有办法基于 type_traits 进行模板重载?
【发布时间】:2017-01-22 20:02:14
【问题描述】:

是否可以根据 type_traits 信息进行函数/类模板重载?

例子:

#include <type_traits>

template<typename Object>
class object_worker
{
public:
    object_worker(Object&& o) // o - is not POD
    {
        // do something
    }
};

template<typename Object>
class object_worker<std::is_pod<Object>::value == true> // how to make this thing work?
{
public:
    object_worker(Object &&o) // o - is POD
    {
        // do something different
    }
};
  • 它必须与某种技术有关吗?比如部分模板特化
  • 如果可以实现,它的名称是什么? (例如部分模板特化概念

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    是的,你可以这样做。它的使用非常广泛。

    template<typename T, bool = is_pod<T>::value>>
    class foo
    {
    };
    
    // This is a partial template specialization.
    // Triggered only when is_pod<T>::value is true
    template<typename T>
    class foo<T, true> // T can be only a POD type
    {
    };
    

    【讨论】:

    • 拯救了我的一天!不应该将第二个模板参数称为 full specialization 吗?我想,partial 类似于:template&lt;typename T*&gt; class cls{};
    • 只希望没有人实例化foo&lt;NonPod, true&gt; x; :-)
    • @KerrekSB 是的,通常最好有一个包装器,或者将它作为 detail 基类。
    • @KerrekSB 很公平 :)
    • @andrgolubev 不,一个完全专业化看起来像`模板类`其中所有模板参数被指定.综上所述,T仍需推演。
    猜你喜欢
    • 2015-03-14
    • 2012-09-23
    • 2012-01-20
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 2017-03-11
    • 2015-04-27
    相关资源
    最近更新 更多