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

Man*_*ork 17 c++ templates typedef c++11

typedef当且仅当满足编译时条件时,我想执行a .如果不满足条件,则根本不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.
};
Run Code Online (Sandbox Code Playgroud)

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

max*_*x66 19

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

// 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>’
 }
Run Code Online (Sandbox Code Playgroud)

  • @chi - 可以做; 使用基类(IMHO)的优点是你可以开发一个简单而轻量级的两个不同的特化,只有(或没有)typedef; 这允许开发可能很复杂的派生类的单个版本. (5认同)

W.F*_*.F. 15

遗憾的是,由于必须已经定义了传递给模板实例化的名称,因此无法获得所需的语法.在您的情况下myType1,myType2不会从编译器的角度命名任何东西.但是,如果您不坚持您提到的语法,可以尝试使用std::enable_if如下:

#include <type_traits>

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

};

int main() {
    A::myType1::type i;
    //A::myType2::type i2; // causes error: no type named 'type' in 'A::myType2'
    (void)i;
}
Run Code Online (Sandbox Code Playgroud)

[现场演示]


编辑:

我想到的另一种方式(利用默认模板参数使用):

#include <type_traits>

struct A {
    template <class T = int>
    using myType1 = typename std::enable_if<true, T>::type;
    template <class T = int>
    using myType2 = typename std::enable_if<false, T>::type;
};

int main() {
    A::myType1<> i;
    //A::myType2<> j;
    (void)i;
}
Run Code Online (Sandbox Code Playgroud)

[现场演示]