Shm*_*opy 5 c++ templates c++14
我想做一个typedef取决于typedef模板参数中是否存在的:
struct foo
{
using MyType = int;
};
template <typename T = foo>
struct bar
{
// Pseudo code
#if T::MyType is defined
using MyType = T::MyType;
#else
using MyType = double;
#endif
};
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以使其std::conditional在C ++ 14中使用?
Sto*_*ica 10
有,有点sfinae。
template<class, typename Fallback, typename = void>
struct type_or_default {
using type = Fallback;
};
template<class C, typename F>
struct type_or_default<C, F, std::void_t<typename C::type>> {
using type = typename C::type;
};
Run Code Online (Sandbox Code Playgroud)
这使用标准约定,其中模板元函数公开成员名称type,但是您可以根据自己的命名需求对其进行调整。这里唯一的非C ++ 14位是std::void_t,但是可以在C ++ 14中实现等效的功能(只是不能放入namespace中std)。您可以在班级中像这样使用它:
template <typename T = foo>
struct bar
{
using type = typename type_or_default<T, double>::type;
};
Run Code Online (Sandbox Code Playgroud)
这里发生的是,编译器在选择模板特化时进行其模式匹配。如果该类C有一个member type,那么我们提供的部分专业化将被认为是更加专业化的,并因此被选择。否则(如果在检查专业化时替换失败),则始终可以使用主模板。
现场节目需要修补。