c++ - 根据模板参数内容执行或跳过代码

标签 c++ templates c++11

我想为任意类型 T 创建一个容器。但是,如果 T 有一个 header 类型的成员(我也定义了),我想添加一些功能。如果 T 没有该 header 成员,则可以跳过添加的功能。

例如,添加的功能可能是根据执行操作的时间添加时间戳。这是我想要的伪代码:

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
    }
};

当然,正如我所说,some_operation 还必须找出类 T 中 my_header 实例的名称。可以通过对要使用的添加功能强加以下要求之一来消除此要求(按顺序从从最优选到最不优选):

  • 类 T 中 my_header 的实例必须具有名称 header
  • my_header的实例是类T中的第一个成员变量
  • 类 T 派生自 my_header 而不是将其作为成员变量包含在内

使用 C++11 没问题(实际上是预期的)。

最佳答案

不是最好的解决方案,但我认为它可以工作。从 How to detect whether there is a specific member variable in class? 窃取代码

#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.
}

关于c++ - 根据模板参数内容执行或跳过代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21151467/

相关文章:

java - 为移动操作系统开发图像到文本转换应用程序

java - Java使用什么技巧来避免>>中的空格?

c++ - 对象声明中的模板 "error: expected expression"

C++ 如何从没有共享父类(super class)的类中调用公共(public)方法?

c# - 我读过 std::list 很糟糕。有人可以将它与 .Net 的 List<> 类型进行比较吗?我要从 C# 转到 C++

c++ - 为什么我收到 "getuid was not declared in that scope"错误?

c++ - 怎么可能在 C++ 中的 main() 中不声明任何内容,但编译后却有一个工作应用程序?

c++ - std::enable_if 和 std::is_arithmetic 作为模板参数的问题

C++ 输入未正确阻塞

c++ - 运行 C++ 程序 eclipse 时出错(没有可构建的内容)