我可以为常数使用模板吗?
May I use a template for a constant?
我想写的代码如下:
template<typename T> const int a;
template<> const int a<float>=5;
template<> const int a<double>=14;
template<> const int a<char>=6;
template<> const int a<wchar>=33;
可以,如果你的编译器支持c++变量模板特性的话。
template<typename T> const int a = 0;
template<> const int a<float> = 5;
template<> const int a<double> = 14;
template<> const int a<char> = 6;
template<> const int a<wchar_t> = 33;
我在专门化的>
和=
之间添加了空格,因为clang遇到解析错误,否则
错误:右括号和等号之间需要空格(使用'> =')
现场演示
所有c++版本(包括c++ 11之前版本)的解决方案:
template<typename T>
struct a { static const int value; };
template<> const int a<float>::value = 5;
template<> const int a<double>::value = 14;
template<> const int a<char>::value = 6;
template<> const int a<wchar_t>::value = 33;
(注意问题使用了wchar
,它不是标准类型)
相关文章:
- 我可以更改将引用参数传递到指针中并使其正常工作的函数的输入(C、C++)吗?
- 为什么我可以更改指针的常数(const char *)槽的值
- 我可以在使用 omp_set_num_threads 后使 OpenMP 恢复到理想的线程 # 吗?
- 我可以以某种方式使我的矢量/数组动态更改装置数量吗?
- 我可以在移动平台上有效地使用用C/C 编写的数字算法
- 我可以定义一个(键入的)常数,该常数确定不占据可执行文件中的空间
- 我可以在 std::list 中移动元素而不会使迭代器或引用无效,但是如何移动呢?
- 我可以将艾根·莱文伯格·马夸特与线性方程和常数雅可比矩阵一起使用吗?
- 有哪些优化技巧可以使我的代码运行得更快
- 我可以在这里不使用线程同步吗?
- 我如何使用关系 btwn 3 整数来确定三角形和/或我可以使用什么声明来使这个程序工作
- 我可以使用字体表构建抽象访问者吗?
- 我可以在 Android Studio 中使用用 Xcode 编译的 C++ 静态库吗?
- 我可以禁止某些函数使程序崩溃吗?
- 我可以使以下代码锁免费/原子吗?
- 仅仅使用(稳定的)第三方库就可以使我的代码无法工作
- 如何使一个回调全局,所以我可以使用它的其他功能
- 无论如何,我可以使模板<类型名T>接受多个值吗?
- 如何改变for循环,使我可以使用eof
- 我可以为常数使用模板吗?