gpt4 book ai didi

c++ - 在模板函数返回类型上使用 std::enable_if 来利用 SFINAE - 编译错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:42:11 25 4
gpt4 key购买 nike

下面的代码

#include <type_traits>

struct CByteArray {};
struct HLVariant {
HLVariant() {}
HLVariant(const HLVariant&) {}
HLVariant(const CByteArray&) {}

};

template <typename T>
inline typename std::enable_if<!std::is_pod<T>::value, CByteArray>::type serialize(const T& value)
{
return serialize(HLVariant(value));
}

template <typename T>
inline typename std::enable_if<std::is_pod<T>::value, CByteArray>::type serialize(const T& value)
{
return CByteArray();
}

template <>
inline CByteArray serialize(const HLVariant& value)
{
return CByteArray();
}

int main()
{
serialize(0);
serialize(CByteArray());
serialize(HLVariant());

return 0;
}

触发编译错误C2794: 'type' : is not a member of any direct or indirect base class of 'std::enable_if<false,CByteArray>'在 MSVC 2013 中。但是,它在 ideone 中工作:enter link description here

这里有什么错误?

错误在 MSVC 2010、2012 和 2013 中是相同的。

最佳答案

我觉得没问题,但我可以通过删除 template<> 来修复它来自 serialize 的最终重载.当正常重载就可以时,无需使其成为完全特化!

编辑:还有什么有用的是提供一个只匹配 HLVariant 的模板特化(并进一步限制其他专业不再匹配 HLVariant ,以避免歧义)。

应该这样做:

http://ideone.com/0UGkcn

#include <type_traits>
#include <iostream>

struct CByteArray {};
struct NonPod {public: int a; private: int b;};
struct HLVariant {
HLVariant() {}
HLVariant(const HLVariant&) {}
HLVariant(const CByteArray&) {}
HLVariant(const NonPod&) {}
};

template <typename T>
inline typename std::enable_if<std::is_same<T, HLVariant>::value && !std::is_pod<T>::value, CByteArray>::type serialize(const T& value)
{
std::cout << "serialize non-pod variant\n";
return CByteArray();
}

template <typename T>
inline typename std::enable_if<!std::is_same<T, HLVariant>::value && !std::is_pod<T>::value, CByteArray>::type serialize(const T& value)
{
std::cout << "serialize non-pod non-variant\n";
return serialize(HLVariant(value));
}

template <typename T>
inline typename std::enable_if<std::is_pod<T>::value, CByteArray>::type serialize(const T& value)
{
std::cout << "serialize pod\n";
return CByteArray();
}

int main()
{
std::cout << "int:\n";
serialize(0);
std::cout << "CByteArray:\n";
serialize(CByteArray());
std::cout << "HLVariant:\n";
serialize(HLVariant());
std::cout << "NonPod:\n";
serialize(NonPod());
}

关于c++ - 在模板函数返回类型上使用 std::enable_if 来利用 SFINAE - 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26716609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com