【发布时间】:2019-04-15 01:31:00
【问题描述】:
这里是MCVE(无法编译):-
#include <iostream>
#include <type_traits>
//-- library ---
template<class T,template<class>class Slot,class DefaultType>
class GetType{
template <typename C> static Slot<T> check( Slot<T>*);
template <typename> static DefaultType check(...);
public: using type=decltype(check<T>());
};
template<class T,template<class>class Slot,class DefaultType>
using X = typename GetType<T,Slot,DefaultType>::type;
这是它的用法:-
//--- user defined ---
class B {public: using MyType=int;};
class C{};
template<class T> using SlotCustom = typename T::MyType;
int main(){
using ShouldInt=X< B ,SlotCustom ,long>; //B::Mytype =int , result:int
using ShouldLong=X< C ,SlotCustom ,long>;//C::Mytype not exist, result:long
std::cout<< std::is_same_v<ShouldInt, int> <<std::cout; //should true
std::cout<< std::is_same_v<ShouldLong, long> <<std::cout; //should true
}
我的目标是创建一个库 typedef X< Param1 ,SlotCustom ,DefaultType>,这意味着如下伪代码:-
if ( SlotCustom<Param1> has meaning) return "SlotCustom<Param1>" ;
else return "DefaultType"; //i.e. by default
怎么做?
Here 是一个类似的问题。
主要区别在于X<T>只能有一个bool,而且很多东西都是硬编码的。
我是模板专业化的新手。解决方案可能很明显,但我找不到。
【问题讨论】:
标签: c++ templates c++14 typedef template-specialization