2017-06-28 131 views
0

鑑於我有一個由枚舉模板化的函數,我想「typedef/alias」函數來簡化它的使用。這裏類似的問題:(Typedef with template functionsC++11: How to alias a function?Typedef模板功能

這裏有三種可能的解決方案,我想出了,而且我不喜歡他們:

  1. 寫宏包的功能。問題:宏(命名空間安全性?)
  2. 靜態函數指針。問題:變量(例如,需要添加#pragma部分以禁用Wunused變量)
  3. 爲每種情況明確寫入函數。問題:創建全新的功能(即不只是重命名原有的功能),更易於出錯的寫入,更多的函數調用
  4. 與3.相同,但內聯保留在標題中。這可能是我的最愛。問題:創建全新的功能(即不只是重命名原有的功能),更多的函數調用

上面列出的方法(除個人不喜歡之外)還有其他特定的優點/缺點嗎?應該不惜一切代價避免?

虛擬實例:

foo_lib.h

#ifndef _FOO_LIB_H_ 
#define _FOO_LIB_H_ 

enum class Score { 
    LOSS = 0, 
    DRAW = 1, 
    WIN = 3 
}; 

void AddScore(int *current_score_p, const Score &score); 

template <Score SCORE> 
void AddScore(int *current_score_p) { 
    AddScore(current_score_p, SCORE); 
} 

// 1. macro 
#define ADD_SCORE_DRAW(current_score_p) AddScore<Score::DRAW>((current_score_p)) 

// 2. static function pointer (auto would work too) 
static void (*AddScoreDrawStatic)(int *current_score_p) = &AddScore<Score::DRAW>; 

// 3. Explicit function for each case 
void AddScoreDrawSpecial(int *current_score_p); 

// 4. Like 3., but inline to keep in header 
inline void AddScoreDrawInline(int *current_score_p) { AddScore<Score::DRAW>(current_score_p); } 

#endif // _FOO_LIB_H_ 

foo_lib.cpp

#include "foo_lib.h" 

void AddScore(int *current_score_p, const Score &score) { 
    *current_score_p += static_cast<int>(score); 
} 

void AddScoreDrawSpecial(int *current_score_p) { 
    AddScore<Score::DRAW>(current_score_p); 
} 

回答

0

如果你的目的是要分數添加到一個整數,並將結果存儲在一個整數中,最簡單的做法是創建一個可以像0123那樣調用的函數它的可讀性很好。另外,我討厭宏。

int add_score(int previous_score, Score score); 

模板與非類型模板參數並不在我看來

+0

感謝這裏提高可讀性。誠然,這也是我最初的功能正在做的事情(除了寫入指針與返回值)。這裏的評分例子只是一個代碼片段,但我需要的真實應用程序有點複雜。 – Cedric

+0

@Cedric能否詳細說明你的真實用例如何比你提出的問題更復雜?這可能會影響我的回答 – Curious

+0

我有一個框架與不同的模塊,由ModuleID(枚舉)標識。然後我有轉換功能,它需要數據來自哪裏以及去哪裏的地方。 AddData(module_id源,module_id本地,數據)。 我想爲每個模塊提供一個版本,所以我可以在模塊「home」中的任何地方都可以說AddDataHome(module_id source,data),而不必每次都傳遞它自己的id。 – Cedric