2014-11-24 39 views
1
#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

谢谢

+2

创建一个函数,并从这两个专业调用它们。 – 0x499602D2 2014-11-24 20:41:44

+0

你可以调用另一个专业 – 2014-11-24 20:46:38

回答

3

正如意见提出由@ 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); 
} 
1

要重新使用多种类型的同种相同的代码,你可以(如果你不使用C++ 11或boost::enable_if)与type traits(一个很好的例子是here)使用std::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++版本使用的相同目的的结构或类)

0

像这应该给你你想要的重用水平:

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