判断类是否包括指定成员函数

BOOST_TTI里面有很多很用用的type traits,实现编译阶段的类型判断。其中BOOST_TTI_HAS_MEMBER_FUNCTION用来判断类是否包括指定成员函数,使用非常方便。

BOOST_TTI_HAS_MEMBER_FUNCTION是一个宏函数,用来生成一个type traits

具体例子如下,BOOST_TTI_HAS_MEMBER_FUNCTION(to_string)将生成一个has_member_function_to_string,用于判断类是否有to_string成员函数:

  • has_member_function_to_string<T, std::string>可用于判断类是否有std::string to_string()成员函数。
  • has_member_function_to_string<const T, std::string>判断类T是否有std::string to_string() const成员函数。
#include <boost/tti/has_member_function.hpp>
#include <string>
#include <iostream>

struct ClassWithToString {
    std::string to_string() {   return "with to_string"; }
};

struct ClassWithToStringConst {
    std::string to_string() const {   return "with to_string"; }
};

struct ClassWithoutToString {

};

BOOST_TTI_HAS_MEMBER_FUNCTION(to_string);

int main() {
    std::cout << std::boolalpha
        << has_member_function_to_string<ClassWithToString, std::string>::value << std::endl
        // true
        << has_member_function_to_string<ClassWithToStringConst, std::string>::value << std::endl
        // false
        << has_member_function_to_string<const ClassWithToStringConst, std::string>::value << std::endl
        // true
        << has_member_function_to_string<ClassWithoutToString, std::string>::value << std::endl;
        // false
}

用这个可以实现很优雅的功能。比如对所有有std::string to_string() const成员函数的类,自动重载<<直接输出to_string()的返回值。

#include <boost/tti/has_member_function.hpp>
#include <string>
#include <iostream>

BOOST_TTI_HAS_MEMBER_FUNCTION(to_string)

template<class T>
std::enable_if<has_member_function_to_string<const T, std::string>::value, std::ostream&>::type
operator<<(std::ostream& out, const T& obj) {
    out << obj.to_string();
}

struct ClassWithToString {
    std::string to_string() const {
        return "Class<ClassWithToString>";
    }
}

int main() {
    ClassWithToString obj;
    std::cout << obj << std::endl;

    return 0;
}
Copyright © zhiqiang.org 2016 all right reserved,powered by Gitbook该文件修订时间: 2016-08-03 01:06:06

results matching ""

    No results matching ""