簡體   English   中英

在C ++中將類型從參數轉換為模板

[英]Transform the type from argument to template in C++

我正在重構一些使用自己的類型處理系統的舊代碼,它為一個類型提供了一個特殊的宏作為參數:

x = function(TYPE(double), y);

重構后,上面的內容寫成

x = function<double>(y);

有沒有辦法(使用宏或重載函數)保持舊樣式工作,提供向后兼容性? 我試過這樣的事情:

#define TYPE(x) (x)
#define function(x, y) function<x>(y)

希望只有當實際的參數個數與其定義匹配時才會使用該宏,但這會導致編譯錯誤。

template< class Type >
void function( int x ) {}

#define TYPE( t ) t()
template< class Type >
void function( Type, int x ) { function< Type >( x ); }

編輯:更一般地說,例如,如果你想支持void ,你可以做...

template< class Type >
void function( int ) {}

template< class Type >
struct TypeCarrier {};

#define TYPE( t ) TypeCarrier< t >()
template< class Type >
void function( TypeCarrier< Type >, int x ) { function< Type >( x ); }

int main()
{
    function( TYPE( double ), 1 );
    function( TYPE( void ), 2 );
}

一個問題是你對TYPE的定義。 擺脫括號。

#define TYPE(x) x
#define function(x, y) function<x> (y)

這也是一個潛在的問題,因為模板函數與您要替換的函數具有相同的名稱。 您可能想要將其命名為不同的名稱。 否則新用法不受限制。

#define TYPE(x) x
#define function(x, y) some_name_other_than_function<x> (y)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM