Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a class template which I use to get the size of a variable:

template <class T>
class Size
{
   unsigned int operator() (T) {return sizeof(T);}
};

This works fine but for strings I want to use strlen instead of sizeof:

template <>
class Size<char *>
{
   unsigned int operator() (char *str) {return strlen(str);}
};

The problem is when I create an instance of size with const char * it goes to the unspecialized version. I was wondering if there is a way to capture both the const and non-const versions of char * in on template specialization? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
254 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use this technique:

#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 */ }
};

EDIT: Example of how to define the methods outside of the class definition.

EDIT2: Added helper to avoid repeating the possibly long and complex condition.

EDIT3: Simplified helper.

#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;
}

which prints

1
2
2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...