如何在C ++ 11中调用模板类型的方法?

时间:2014-02-28 22:35:51

标签: c++ templates c++11

如何在C ++ 11中调用模板类型的方法?

示例:

template <typename T>
void f(T t) {
    // How to call a method here like t.method()?
}

这在C ++ 11中是否可能以某种方式首先检查T是否具有该方法, 如果它然后使用它?

2 个答案:

答案 0 :(得分:6)

C ++模板因缺乏约束而获得大部分功能(以及狡猾的错误消息)。您可以将模板视为由编译器为其调用的每种不同类型进行“复制和粘贴”(除了预处理器之外,编译器实际上知道类型是什么,并且不会使用文字字符串替换)

只需调用假定存在的方法,如果用户传入的类型没有该方法,则会生成编译器错误。

template <typename T>
void f(T t) {
    t.method();      // Generates error unless `method` really is a member of T
}

这也可以让这样的代码工作:

template <typename T>
void less(T const& a, T const& b) { return a < b; }

assert(less(1, 2));    // Works as expected

struct NonComparable { };
less(NonComparable(), NonComparable());   // Error

答案 1 :(得分:-1)

看一下Boost Type Traits Introspection库。