c++ - const 和非 const 模板特化

标签 c++ templates

我有一个类模板,我用它来获取变量的大小:

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

这很好用,但对于字符串我想使用 strlen 而不是 sizeof:

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

问题是当我使用 const char * 创建 size 的实例时,它会转到非专业版本。我想知道是否有办法在模板特化中同时捕获 char * 的 const 和非 const 版本?谢谢。

最佳答案

使用这种技术:

#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

关于c++ - const 和非 const 模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14926482/

相关文章:

C++ 不允许我从基类调用公共(public)方法

html - Haml 继承模板

javascript - ListView 与 NumericTextBox 数据初始化

c++ - 使用 iostream read 和 signed char 时的未定义行为

c++ - 使用 OpenCV 非自由库时 vector 未定义

c++ - 类模板 - 找不到合适的运算符方法

c++ - 动态数组推送功能 - 它是如何工作的?

c++ - 是否可以创建具有稍后类型定义的模板类?

c++ - STL算法类似于transform,允许访问先前转换的元素,类似于accumulate

c++ - 如何找到内存泄漏的位置?