Const and non const template specialization(const 和非 const 模板特化)
问题描述
我有一个类模板,用于获取变量的大小:
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);}
};
这很好用,但对于字符串我想使用 strlen 而不是 sizeof:
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);}
};
问题是当我用 const char * 创建一个 size 实例时,它会转到非专业化版本.我想知道是否有办法在模板特化中同时捕获 char * 的常量和非常量版本?谢谢.
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.
推荐答案
使用这个技巧:
#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 */ }
};
如何在类定义之外定义方法的示例.
Example of how to define the methods outside of the class definition.
添加了帮助程序以避免重复可能的冗长和复杂的条件.
Added helper to avoid repeating the possibly long and complex condition.
简化的助手.
#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
这篇关于const 和非 const 模板特化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:const 和非 const 模板特化
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
