使用这种技术:
#include <type_traits>
template< typename T, typename = void >
class Size
{
unsigned int operator() (T) {return sizeof(T);}
};
template< typename T >
class Size< T, typename std::enable_if<
std::is_same< T, char* >::value ||
std::is_same< T, const char* >::value
>::type >
{
unsigned int operator() ( T str ) { /* your code here */ }
};
编辑:如何在类定义之外定义方法的示例。
EDIT2:添加了帮助程序以避免重复可能冗长而复杂的情况。
EDIT3:简化的助手。
#include <type_traits>
#include <iostream>
template< typename T >
struct my_condition
: std::enable_if< std::is_same< T, char* >::value ||
std::is_same< T, const char* >::value >
{};
template< typename T, typename = void >
struct Size
{
unsigned int operator() (T);
};
template< typename T >
struct Size< T, typename my_condition< T >::type >
{
unsigned int operator() (T);
};
template< typename T, typename Dummy >
unsigned int Size< T, Dummy >::operator() (T)
{
return 1;
}
template< typename T >
unsigned int Size< T, typename my_condition< T >::type >::operator() (T)
{
return 2;
}
int main()
{
std::cout << Size< int >()(0) << std::endl;
std::cout << Size< char* >()(0) << std::endl;
std::cout << Size< const char* >()(0) << std::endl;
}
哪个打印
1
2
2