Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there way to perform "if (condition) typedef ..."

I would like to perform a typedef, if and only if a compile-time condition is met. If the condition is not met, no typedef shall be performed at all.

Is that possible in C++11?

Example:

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

I am looking for this fictional std::conditional_typedef.

like image 217
ManuelAtWork Avatar asked Dec 01 '16 09:12

ManuelAtWork


People also ask

Can you typedef a typedef?

Typedef cannot be used to change the meaning of an existing type name (including a typedef-name). Once declared, a typedef-name may only be redeclared to refer to the same type again.

What is the syntax of a typedef?

The syntax of typedef is as follows: Syntax: typedef data_type new_name; typedef : It is a keyword. data_type : It is the name of any existing type or user defined type created using structure/union. new_name : alias or new name you want to give to any existing type or user defined type.

Does typedef have scope?

A typedef is scoped exactly as the object declaration would have been, so it can be file scoped or local to a block or (in C++) to a namespace or class.

What is typedef when it will be used?

typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.


1 Answers

Another way can be passing from the specialization of a base class

// 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>’
 }
like image 155
max66 Avatar answered Sep 26 '22 23:09

max66