c++ - 有没有办法执行 "if (condition) typedef ..."

标签 c++ c++11 templates typedef

当且仅当满足编译时条件时,我想执行 typedef。如果条件不满足,则根本不执行typedef

这在 C++11 中可行吗?

例子:

class A {
  std::conditional_typedef<true,int,myType1>; // Performs "typedef int myType1".
  std::conditional_typedef<false,int,myType2>; // Does nothing at all.
};

我正在寻找这个虚构的 std::conditional_typedef

最佳答案

另一种方法是从基类的特化中传递

// foo is a light struct (only a typedef or not at all) that can be
// developed in two versions

template <bool>
struct foo;

template <>
struct foo<true>
 { typedef int myType1; }; // or using myType1 = int;

template <>
struct foo<false>
 { };

template <bool B>
struct bar : public foo<B> // B can be a type_traits value derived
                           // from template arguments for bar
 {
   // potential complex struct or class, developed only one time 
 };


int main()
 {
   bar<true>::myType1 mt1 { 1 };
   // bar<false>::myType1 mt2 { 1 }; error: ‘myType1’ is not a member of ‘bar<false>’
 }

关于c++ - 有没有办法执行 "if (condition) typedef ...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40907467/

相关文章:

c++是否可以将对象类型传递给要与之比较的函数

c++ - 使函数模板的某些特化成为 friend

c++ - 使用两个线程和system()命令运行shell脚本: how to make sure that one shell script is started before another

c# - 调用 native C++ 方法时在 Debug模式 (F5) 下崩溃

c++ - 当我们使用基指针新建派生类时调用派生类的构造函数

c++ - 从双向链表中删除节点

C++ 可变参数模板异常示例

c++ - C++模板-在类外部实现

c++ - 编译时素数检查

c++ - 逻辑设计模式