如何解决C ++模板替代规则
我正在尝试为实现成员函数的特定类型覆盖C ++模板。在我看来,当前的语言规范无法做到这一点。
如果我对一种特定类型使用专门化,则覆盖仅适用。
代码始终打印World而不是Hello。
有什么办法告诉编译器使用其他模板吗?
我无法修改serialize()的第一个模板,因为它是外部库的一部分。我可以添加其他模板。
#include <iostream>
#include <type_traits>
#include <new>
struct PanelBarcode
{
std::string value;
template<class S> void Serialize(S& in_s)
{
std::cout << value;
}
};
template <typename Archive,typename C>
struct has_serialize
{
private:
template<typename T>
static constexpr auto check(T*)
-> typename
std::is_same<
decltype(std::declval<T>().Serialize(std::declval<Archive&>())),void
>::type;
template<typename>
static constexpr std::false_type check(...);
typedef decltype(check<C>(0)) type;
public:
static constexpr bool value = type::value;
};
struct X {
X() {}
template<class S> void Serialize(S& in_s)
{ }
};
template<class A,class T>
void serialize(A ar,T& obj,const unsigned int version)
{
std::cout << "World";
}
template<class A,class T,typename std::enable_if_t<has_serialize<A,T>::value> * = nullptr>
void serialize(A ar,const unsigned int version)
{
obj.Serialize(ar);
}
struct Y
{
Y() {}
};
int main()
{
PanelBarcode bc;
bc.value = "Hello";
Y y;
serialize<Y,PanelBarcode>(y,bc,13);
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。