以下代码尝试为条目建模具有不同类型的通用表(其中每个条目包含键和值)。 在函数“compareKeyWithEntry()”中,我们需要使用相关键的类型作为成员函数的签名;为了达到这个目的,使用了decltype。
#include <iostream>
struct Key {
int a;
};
bool operator ==(const Key &key_1, const Key &key_2) {
return ( key_1.a == key_2.a );
}
struct Value {
int b;
};
struct Entry {
Key key;
Value val;
};
template <typename Entry>
class Table
{
public:
Table(){}
template <typename Key_T = decltype(Entry::key)>
bool compareKeyWithEntry(const Entry& entry, const Key_T& key) {
return operator==(entry.key, key);
}
};
int main()
{
Entry e = { { 1, 2} };
Table<Entry> table;
std::cout << table.compareKeyWithEntry(e, e.key) << std::endl;
}
当前的代码是功能性的并且实现了目标。但是,没有'decltype'可以获得相同的结果吗? (使用C ++ 03)
您无法获得该成员的类型,但SFINAE可以通过询问某些类型是否与成员的类型相同来实现您想要的。
typedef char yes_type;
struct no_type { char arr[2]; };
template <typename Key, typename Entry>
struct is_key_of
{
private:
static yes_type test(Key Entry::*);
static no_type test(...);
public:
static bool const value = sizeof(test(&Entry::key)) == sizeof(yes_type);
};
template <bool> struct static_assertion;
template <> struct static_assertion<true> {};
#define OWN_STATIC_ASSERT(x) ((void)static_assertion<(x)>())
struct Key {
int a;
};
bool operator ==(const Key &key_1, const Key &key_2) {
return ( key_1.a == key_2.a );
}
struct Value {
int b;
};
struct Entry {
Key key;
Value val;
};
template <typename Entry>
class Table
{
public:
Table(){}
template <typename Key_T>
bool compareKeyWithEntry(const Entry& entry, const Key_T& key) {
OWN_STATIC_ASSERT((is_key_of<Key_T, Entry>::value));
return operator==(entry.key, key);
}
};
int main()
{
Entry e = { { 1 }, { 2 } };
Table<Entry> table;
table.compareKeyWithEntry(e, e.key);
//table.compareKeyWithEntry(e, 0); // static assertation raises
}
你可以在返回类型上用enable_if
替换静态断言,如果你想删除像你的decltype
问题那样的重载。