我想为任意类型 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/