Run or skip code based on template content

I want to create a container for an arbitrary type T. However, I want to add some functionality if T has a member, which is a type of header (which I also define). If T does not have this header element, the added functionality can simply be skipped.

The added functionality may, for example, consist of adding a time stamp based on the operation. Here's the pseudo code for what I want:

struct my_header {
  timestamp_t time;
  // ... etc ...
}

template <class T>
class my_container {
  public:
    void some_operation(T val) {
        // condition evaluated at compile time
        if T has a member of type my_header {
            val.header.time = get_current_time();
            // ... etc ...
        }

        // other operations, agnostic to T
    }
};

Of course, like mine, some_operation should also define the instance name my_header in class T. This requirement could be eliminated by imposing one of the following requirements for additional functions that will be used (in order of least preferred):

  • my_header T header
  • my_header - T
  • T my_header , -.

++ 11 ( ).

+4
2

, , . , -?

#include <iostream>
#include <type_traits>

struct my_header {
  int time;
};

// begin stolen code
template<typename T, typename V = bool>
struct has_header : std::false_type { };

template<typename T>
struct has_header<T, 
    typename std::enable_if<
        !std::is_same<decltype(std::declval<T>().header), void>::value, 
        bool
        >::type
    > : std::true_type { };
// end stolen code

struct foo
{
    my_header header;
};

template<typename, typename = void>
class my_container;

template<typename T>
class my_container<T, typename std::enable_if<has_header<T>::value>::type>
{
public:
    T val;
    void foo()
    {
        std::cout << val.header.time << "\n";
    }
};

template <typename T>
class my_container<T, typename std::enable_if<!has_header<T>::value>::type>
{
public:
    T val;
    void foo()
    {
        std::cout << "other.\n";
    }
};

int main()
{
    my_container<foo> c;
    my_container<int> c2;
    c.foo(); // garbage
    c2.foo(); // other.
}
+1

remyable solution (+1), :

#include <iostream>
#include <type_traits>

struct my_header {
  int time = 0;
};

template<typename T>
using has_header = std::is_same< decltype( T::header ), my_header >;

struct foo
{
    my_header header;
};

template<typename T, typename = void>
class my_container
{
public:
    T val;
    void foo()
    {
        std::cout << "other.\n";
    }
};

template<typename T>
class my_container<T, typename std::enable_if<has_header<T>::value>::type>
{
public:
    T val;
    void foo()
    {
        std::cout << "time: " << val.header.time << "\n";
    }
};

int main()
{
    my_container<foo> c;
    my_container<int> c2;
    c.foo(); // time: 0
    c2.foo(); // other.
}

, - , - header, ++ , .

+1

All Articles