在宏内部使用模板

时间:2017-06-11 14:53:28

标签: c++ c++11

我正在研究基于宏参数创建不同名称的类的代码。问题是这个类使用模板。这是我的代码

#define CHECK(exp,from,to) \
template<bool T> \
class _##to{ }; \
\
template<> class _##to<true>{ \
public: \
     _##to(...); \
};\
\
class _##from{ };\
_##to<exp>(_##from);\

但是我收到了这个错误:

error: a template declaration cannot appear at block scope|

所以,如果我不能在块范围内使用模板,那么有没有解决方案?

编辑:

这是我的全部代码:

#define CHECK(exp,from,to) \
template<bool T> \
class _##to{ }; \
\
template<> class _##to<true>{ \
public: \
     _##to(...); \
};\
\
class _##from{ };\
_##to<exp>(_##from);\

template<class TO,class FROM>
void safe_cast(FROM&){
     CHECK(sizeof(FROM)>=sizeof(TO),FROM,TO); //For calling macro
}

int main(){
     float f=90;
     safe_cast<int>(f);
}

0 个答案:

没有答案