首页 > 解决方案 > 具有两种以上类型的 C++ 条件 typedef

问题描述

我正在尝试做这样的事情。

if (flow1)
  {
     typedef template_class<user_defined_type1> x;
  }
else if (flow2)
  {
     typedef template_class<user_defined_type2> x;
  }
else if (flow3)
  {
     typedef template_class<user_defined_type3> x;
  }
else 
  {
     typedef template_class<user_defined_type4> x;
  }

我检查了这个问题的答案How to make a conditional typedef in C++ 但我不确定如果我有超过 1 种类型如何使用 std::conditional ?甚至有可能做这样的事情吗?

标签: c++c++11c++-standard-library

解决方案


Juse 使用多个嵌套std::conditional,例如:

#include <type_traits>

using x = std::conditional<flow1,
        template_class<user_defined_type1>,
        std::conditional<flow2,
            template_class<user_defined_type2>,
            std::conditional<flow3,
                template_class<user_defined_type3>,
                template_class<user_defined_type4>
            >::type
        >::type
    >::type;

/* or, using std::conditional_t in C++14:
using x = std::conditional_t<flow1,
        template_class<user_defined_type1>,
        std::conditional_t<flow2,
            template_class<user_defined_type2>,
            std::conditional_t<flow3,
                template_class<user_defined_type3>,
                template_class<user_defined_type4>
            >
        >
    >;
*/

或者:

#include <type_traits>

using x = template_class<
    std::conditional<flow1,
        user_defined_type1,
        std::conditional<flow2,
            user_defined_type2,
            std::conditional<flow3,
                user_defined_type3,
                user_defined_type4
            >::type
        >::type
    >::type
>;

/* or, using std::conditional_t in C++14:
using x = template_class<
    std::conditional_t<flow1,
        user_defined_type1,
        std::conditional_t<flow2,
            user_defined_type2,
            std::conditional_t<flow3,
                user_defined_type3,
                user_defined_type4
            >
        >
    >
>;
*/

推荐阅读