c++ - 条件显式模板实例化

标签 c++ templates c++11

除了预处理器,我如何有条件地启用/禁用显式模板实例化?

考虑:

template <typename T> struct TheTemplate{ /* blah */ };

template struct TheTemplate<Type1>;
template struct TheTemplate<Type2>;
template struct TheTemplate<Type3>;
template struct TheTemplate<Type4>;

在某些编译条件下,Type3与Type1相同,Type4与Type2相同。发生这种情况时,我会收到错误消息。我想检测类型是否相同,而不是像

中那样在 Type3 和 Type4 上实例化
// this does not work
template struct TheTemplate<Type1>;
template struct TheTemplate<Type2>;
template struct TheTemplate<enable_if<!is_same<Type1, Type3>::value, Type3>::type>;
template struct TheTemplate<enable_if<!is_same<Type2, Type4>::value, Type4>::type>;

我转移了自己的注意力来尝试 enable_if 和 SFINAE(我相信我知道它们失败的原因),但只有预处理器有效(呃)。我正在考虑将类型放入元组或可变参数中,删除重复项,然后使用其余部分进行实例化。

有没有一种方法可以根据模板参数类型有条件地启用/禁用显式模板实例化?

最佳答案

template <typename T> struct TheTemplate{ /* blah */ };

template<int> struct dummy { };

template struct TheTemplate<Type1>;
template struct TheTemplate<Type2>;
template struct TheTemplate<conditional<is_same<Type1, Type3>::value, dummy<3>, Type3>::type>;
template struct TheTemplate<conditional<is_same<Type2, Type4>::value, dummy<4>, Type4>::type>;

这仍然会产生四个显式实例化,但在 Type3 的情况下它们不会重复。与Type1相同(除非 Type1dummy<3> !)

关于c++ - 条件显式模板实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13925730/

相关文章:

ruby-on-rails - Rails 条件布局 : Why does ":for" work as an option for the layout method?

C++ 模板 - 错误 : expected initializer before '<' token

c++ - 如何处理: redeclaration of C++ built-in type ‘char16_t’

c++ - wchar_t 只是 unsigned short 的 typedef 吗?

c++ - 如何直接从分配的内存中执行 mmaped 二进制/代码

c++ - 如何在模板函数中为整数类型选择snprinf掩码?

c++ - 如何在我的 Boost::asio tcp 服务器刚开始运行时启动 "event"(AKA io_service.run())?

c++ - 可以推断左值引用非类型模板参数吗?

c++ - 是否可以用 lambda 初始化静态变量?

c++ - 如何从命令行使用 Visual Studio 2017 Codegen ClangC2?