2014-12-29 201 views
3

如何創建類型副本?例如,如何創建不能隱式轉換爲double(或任何其他數字類型)的類型Mass,AccelerationForce,但其他方式具有double的所有特徵。這將允許編譯時輸入合法性檢查此功能:創建類型副本

Force GetForceNeeded(Mass m, Acceleration a); 

確保GetForceNeeded只能Mass類型和Acceleration的參數來調用。

當然,我可以手動創建的類型的副本實現這一目標:

class Force final 
{ 
public: 
//overload all operators 
private: 
double value; 
}; 

但是這很麻煩。有沒有通用的解決方案?

+2

也許模板?或者使用Boost.Units? –

+2

嗯請問什麼? –

+0

@KerrekSB但是,我如何公開所有定義的操作?假設我想爲「串」做這件事? – Pradhan

回答

5

正如許多評論員指出的,一種解決方案是使用BOOST_STRONG_TYPEDEF,它提供了問題中所需的所有功能。下面是使用例子從自己的文件:

#include <boost/serialization/strong_typedef.hpp> 


BOOST_STRONG_TYPEDEF(int, a) 
void f(int x); // (1) function to handle simple integers 
void f(a x); // (2) special function to handle integers of type a 
int main(){ 
    int x = 1; 
    a y; 
    y = x;  // other operations permitted as a is converted as necessary 
    f(x);  // chooses (1) 
    f(y);  // chooses (2) 
} typedef int a; 

有一個proposal不透明類型定義添加到C++ 1Y。

(我要離開這個答案,因爲我無法找到一個確切的重複數據刪除技術。請標誌,如果事實並非如此。)