C++11 SFINAE设置别名模板
我想知道是否可以根据traits类中是否存在别名,使用SFINAE在不同的类中设置别名模板C++11 SFINAE设置别名模板,c++11,sfinae,template-aliases,C++11,Sfinae,Template Aliases,我想知道是否可以根据traits类中是否存在别名,使用SFINAE在不同的类中设置别名模板 template<class T> struct Foo_Traits; struct Foo1; template<> struct Foo_Traits<Foo1> { using type1 = Bar1; using type2 = Bar2; }; struct Foo2; template<> struct Foo_Traits
template<class T>
struct Foo_Traits;
struct Foo1;
template<>
struct Foo_Traits<Foo1>
{
using type1 = Bar1;
using type2 = Bar2;
};
struct Foo2;
template<>
struct Foo_Traits <Foo2>
{
using type1 = Bar3;
};
您的答案可以在建议的
void\u t
中找到
鉴于:
template <typename...>
using void_t = void;
我们不能直接使用这个谓词,但我们可以根据需要修改它
template <typename ImplT>
class FooBase
{
using T1 = typename Foo_Traits<ImplT>::type1;
template <typename, typename = void>
struct type2_or_type1 {
using type = T1;
};
template <typename T>
struct type2_or_type1<T, void_t<typename T::type2>> {
using type = typename T::type2;
};
using T2 = typename type2_or_type1<Foo_Traits<ImplT>>::type;
};
模板
类食品库
{
使用T1=typename Foo_Traits::type1;
模板
结构类型2或结构类型1{
使用类型=T1;
};
模板
结构类型2或结构类型1{
使用type=typename T::type2;
};
使用T2=typename-type2\u或\u-type1::type;
};
我想这解决了我的std::conditionaltypename Foo_Traits::type2中一半的问题,因此它不会编译。我可以将一个类型添加到结构has_type2_membe
r中,但即使对于true_type
我也会得到一个错误,即type2不是成员。我遗漏了什么吗?编辑了答案以填补遗漏的部分。这与我尝试的各种事情中的一个非常接近,但错误仍然是一样的错误C2039:“type2”:不是“Foo_Traits”的成员
我有一个样本,在题为“实现解决方案”的网站论文中的第2.3节
。我已经用变通版本替换了void\t
的首选实现,它似乎工作得很好。样品在。
template <typename...>
using void_t = void;
template <typename, typename = void>
struct has_type2_member : std::false_type {};
template <typename T>
struct has_type2_member<T, void_t<typename T::type2>> : std::true_type {};
template <typename ImplT>
class FooBase
{
using T1 = typename Foo_Traits<ImplT>::type1;
template <typename, typename = void>
struct type2_or_type1 {
using type = T1;
};
template <typename T>
struct type2_or_type1<T, void_t<typename T::type2>> {
using type = typename T::type2;
};
using T2 = typename type2_or_type1<Foo_Traits<ImplT>>::type;
};