MyMSDN

MyMSDN记录开发新知道

C++ Traits

本来想好好写写C++ Traits的,刚刚接到interview的通知,先贴代码,改天再议。

/*
 * cpp_traits.cpp
 *
 *  Created on: 2010-4-26
 *      Author: volnet@tom.com
 */
#include <iostream>
// kinds of types for overloading.
struct undefined_type {};
struct int32_type {};
struct int64_type {};

// typedef some has_trivial_* for difference types.
template <class T>
struct type_traits {
    typedef undefined_type has_trivial_type;
};

// define the partial specialization functions.
template <>
struct type_traits<int> {
    typedef int32_type has_trivial_type;
};
template <>
struct type_traits<long> {
    typedef int64_type has_trivial_type;
};

// the dispatcher method for all kinds of types.
template <class T>
void type_detect(T& p){
    typedef typename type_traits<T>::has_trivial_type trivial_type;
    type_detect(p, trivial_type());
}

// define the functions for dispatching.
template <class T>
void type_detect(T& p, undefined_type) {
    std::cout << p;
    std::cout << " // It's a undefined type, we have NOT found the dispatcher function." << std::endl;
}
template <class T>
void type_detect(T& p, int32_type) {
    std::cout << p;
    std::cout << " // It's a int32" << std::endl;
}
template <class T>
void type_detect(T& p, int64_type) {
    std::cout << p;
    std::cout << " // It's a int64" << std::endl;
}

int main(void) {
    int int32num = 2010;
    type_detect(int32num);

    long int64num = 2010L;
    type_detect(int64num);

    std::string str = "2010";
    type_detect(str);

    std::cout << "-------end of program." << std::endl;
    return EXIT_SUCCESS;
}

posted on 2010-04-26 15:31 volnet 阅读(721) 评论(2)  编辑 收藏 引用 所属分类: C/C++

评论

# re: C++ Traits 2010-06-03 15:57 brainpoint

特化代码写得不够美啊  回复  更多评论   

# re: C++ Traits 2010-08-29 17:30 evening dresses

template <class T>
  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


特殊功能