如何重用函数专用化代码
How to reuse function specialization code?
#include <iostream>
using namespace std;
template<typename T>
void fun(const T & val)
{
cout << " T " << endl;
}
template<>
void fun<int>(const int & val)
{
cout << " specialization same code " << val << endl;
}
template<>
void fun<double>(const double& val)
{
cout << " specialization same code " << val << endl;
}
int main()
{
fun( 1 );
fun( 1.0 );
fun( 'c' );
return 0;
}
问题>有没有办法重用函数专用化代码?例如,假设 'int 和 'double' 专用化具有完全相同的实现代码。有没有一种方法可以防止代码重复?
http://codepad.org/awGYWiWv
谢谢
正如@0x499602D2在注释中建议的那样,创建另一个函数并确保它仅在int
或double
被调用。
template<typename T>
void bar(const T & val)
{
// Make sure this gets called only for int or double.
static_assert(std::is_same<T, int>::value || std::is_same<T, double>::value);
// Do useful stuff with val.
}
template<>
void fun<int>(const int & val)
{
bar(val);
}
template<>
void fun<double>(const double& val)
{
bar(val);
}
要对相同类型的多种类型重用相同的代码,您可以将std::enable_if
(如果不使用 C++11),则可以使用 boost::enable_if
类型特征(这里是一个很好的例子)。
例如:
template<typename T>
typename std::enable_if<std::is_floating_point<T>::value, T>::type
fun(const T& val)
{
cout << " floating point specialisation " << val << endl;
}
(此类函数专用化仅适用于 C++11,但在旧C++版本中,您可以将结构或类用于相同的目的)
这样的东西应该给你你想要的重用级别:
#include <iostream>
#include <type_traits>
using namespace std;
// will only compile if T is an arithmetic type
template<typename T,
typename std::enable_if<
std::is_arithmetic<T>::value>::type* = nullptr>
void fun(T val)
{
cout << "the square is " << val * val << endl;
}
int main()
{
int x = 10;
double y = 10;
fun(x);
fun(y);
return 0;
}
相关文章:
- .cpp和.h文件中的模板专用化声明
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 两种专用方法中的相同代码
- 在两个派生类之间执行专用代码
- C++ 代码生成和模板专用化
- C++ - 模板类专用化是否有办法包含常规模板中的代码
- 是否允许在模板专用化时从int转换为long(应该编译此代码)
- 如何使用type_traits生成依赖于是否存在类专用化的代码?
- 热以初始化专用模板代码中的静态 const 成员
- 模板部分专用化:如何避免代码重复
- 如何重用函数专用化代码
- 基于标记调度的专用化,用于C++代码中的平台识别和仿真
- 为什么我不能调用以下代码的C++显式专用化版本?
- 为什么允许此模板代码违反C++的专用访问说明符?
- 代码重复和模板专用化(当专用函数具有不同的返回类型时)
- 如何为函数模板(字符串的冒泡排序数组)编写显式专用化代码
- 避免在多个 C++ 模板专用化上重复代码