模板函数覆盖

问题描述 投票:0回答:1

我正在尝试为基于类型的函数创建一个专业化模板

例如对于我拥有的型号

template <class ElementType, typename = typename TEnableIf<TNot<TIsSame<ElementType, double>>::Value>::Type>
    void WriteExtras(IGLTFJsonWriter& Writer, const FString& Key, const TSharedPtr<FJsonValue>& Value) const
    {
        Writer.Write(Key, float(Value->AsNumber()));
        // Perform further processing or write logic for double
    

}

现在我想要多一个定义,但对于 bool ......但如果我尝试这样做

 template <class ElementType, typename = typename TEnableIf<TNot<TIsSame<ElementType, bool>>::Value>::Type>
        void WriteExtras(IGLTFJsonWriter& Writer, const FString& Key, const TSharedPtr<FJsonValue>& Value) const
        {
            Writer.Write(Key, Value->AsBool());
            // Perform further processing or write logic for double
        

}

我收到错误“函数已定义”

我将函数模板称为

WriteExtras< EJson>(Writer,Key,Pair.Value);

EJson 是一个枚举

enum class EJson
{
    None,
    Null,
    String,
    Number,
    Boolean,
    Array,
    Object
};
c++ templates variadic-templates template-specialization
1个回答
0
投票

这两个函数实际上声明了同一个函数:

template <class ElementType, typename = typename TEnableIf<TNot<TIsSame<ElementType, double>>::Value>::Type>
void WriteExtras(IGLTFJsonWriter& Writer, const FString& Key, const TSharedPtr<FJsonValue>& Value) const;

template <class ElementType, typename = typename TEnableIf<TNot<TIsSame<ElementType, bool>>::Value>::Type>
void WriteExtras(IGLTFJsonWriter& Writer, const FString& Key, const TSharedPtr<FJsonValue>& Value) const;

它们之间的唯一区别是模板参数的默认参数,但这并没有使其中之一成为单独的实体。就像写作一样:

int foo(int x = 0); 
int foo(int x = 1);

您需要在函数签名中的其他地方使用

std::enable_if
(或您的自定义模仿)进行 SFINAE,例如参数、noexcept 规范、返回类型等。对于函数,最好的方法之一是使用返回类型,因为它不会改变模板参数列表:

// convenience alias (since C++14)
template <bool Condition, typename T = void>
using EnableIf_t = typename EnableIf<Condition, T>::type;

template <class ElementType>
auto WriteExtras(IGLTFJsonWriter& Writer, const FString& Key, const TSharedPtr<FJsonValue>& Value) const
  -> TEnableIf_t<not TIsSame<ElementType, double>::Value>;

template <class ElementType>
auto WriteExtras(IGLTFJsonWriter& Writer, const FString& Key, const TSharedPtr<FJsonValue>& Value) const
  -> TEnableIf_t<not TIsSame<ElementType, bool>::Value>;
© www.soinside.com 2019 - 2024. All rights reserved.