下面的类完成在编译时检查类型T是否可以转化成类型U:

template <class T, class U>
class Conversion
{
public:
    enum
    {
	/*这里很巧妙:MakeT()返回一个T类型,此时如果T可以转化成U,那么会调用static Small Test(U);返回一个Small类型,从而exists会在编译期间就被确定成1;如果T不能转化成U,则会调用static Big   Test(...)返回一个Big类型,从而exists会在编译期间就被确定成0*/
        exists = sizeof(Test(MakeT()))==sizeof(Small)
    };
    enum
    {
        sameType = false;
    };
private:
    typedef char Small;
    class Big { char dummy[2]; };

    static Small Test(U);
    static Big   Test(...);
    static T     MakeT();
};

//针对同一类型的模板特化
typename <class T>
class Conversion<T,T>
{
public:
    enum { exists = 1, sameType = 1 };
};

int main()
{
    std::cout   << Conversion<double, int>::exists <<
                << Conversion<char, char*>::exists <<
                << Conversion<std::vector<int>,std::list<int> >::exists
                << std::endl;
    return 0;
}
 

源代码引用自:http://aszt.inf.elte.hu/~gsd/halado_cpp/ch06s10.html

版权归原作者所有!

相关文章:

  • 2021-05-22
  • 2022-12-23
  • 2021-11-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-17
猜你喜欢
  • 2022-02-07
  • 2021-10-10
  • 2022-12-23
  • 2022-12-23
  • 2021-12-17
  • 2022-12-23
  • 2022-02-24
相关资源
相似解决方案