Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring member or not depending on template parameter

Is it possible to declare or not a member variable depending on template condition without using dummy empty type?

Example:

struct empty{};
struct real_type{};

template<bool condition>
struct foo
{
    typename std::conditional<condition, real_type, empty>::type _member;
};
like image 629
Mircea Ispas Avatar asked May 21 '13 14:05

Mircea Ispas


People also ask

Which is correct example of template parameters?

Template Parameters: These names are listed after the template keyword in a template declaration. For example, T is the single template parameter specified in our Stack example given earlier. Template Arguments: These entities are substituted for template parameters during specialization.

What is a non-type template parameter?

A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.

Can we use non-type parameters as argument templates?

A non-type template argument provided within a template argument list is an expression whose value can be determined at compile time. Such arguments must be constant expressions, addresses of functions or objects with external linkage, or addresses of static class members.

What is the purpose of template parameter?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.


1 Answers

You can derive from a template that has a specialization:

struct real_type { };

template<bool c>
struct foo_base { };

template<>
struct foo_base<true>
{
    real_type _member;
};

template<bool condition>
struct foo : foo_base<condition>
{
};

As a small test:

int main()
{
    foo<true> t;
    t._member.x = 42; // OK

    foo<false> f;
    f._member.x = 42; // ERROR! No _member exists
}
like image 79
Andy Prowl Avatar answered Nov 01 '22 10:11

Andy Prowl