如何重用函数专用化代码

How to reuse function specialization code?

本文关键字:代码 专用 函数 何重用      更新时间:2023-10-16
#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在注释中建议的那样,创建另一个函数并确保它仅在intdouble被调用。

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