当且仅当满足编译时条件时,我想执行 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/