我有以下問題。假設我有一個header.hpp帶有這個模板函式宣告的頭檔案:
template <typename T> extern T func();
在header.cpp檔案中我有函式定義:
template <typename T> T func() { \* do something */ };
//Following lines are for explicit istantiation of the template for some types:
template double func <double> (); //1
template int func <int>(); //2
//And others...
是否存在一個函式/類或其他允許我為更多模板型別顯式實體化模板類定義的函式/類,而無需每次都撰寫類似前面代碼的第 1 行或第 2 行的東西?
我正在尋找類似的東西,例如:
void function ( template_function list_of_types )
{
//explicit istantiations of the template_function for the types given in the list_of_types container...
}
簽名不必像上面那樣,但也相似,重要的是它像我之前所說的那樣作業。謝謝。
uj5u.com熱心網友回復:
沒有這樣的功能。顯式模板實體化必須出現在命名空間范圍內,因此像這樣的“函式”必須是某種編譯器魔法(不存在),或者使用前處理器擴展為所需的宣告。
像Boost.PP這樣的東西有機器來近似你所追求的。舉個例子:
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/tuple/to_seq.hpp>
#define ARGS(...) BOOST_PP_TUPLE_TO_SEQ((__VA_ARGS__))
template <typename T> void func(T) { };
#define EXPANSION(r, data, elem) template void func<elem>(elem);
BOOST_PP_SEQ_FOR_EACH(EXPANSION, _, ARGS(int,double,char))
現場查看 preprcoessor 輸出。
它可能會刺激那些對前處理器過敏的人,但它是為數不多的用于預處理的合法用途之一。至少在 C 標準委員會選擇為我們提供更好的工具之前。
uj5u.com熱心網友回復:
您可以使用概念(或要求)并創建模板的專用版本。
所以如果你有
void func(auto t) { ...}
您可以定義一個概念“AllowedNumericalTypes”并撰寫另一個模板,例如
void func(AllowedNumericalTypes auto t) { /*1 and 2 */ }
編譯器將選擇最匹配的 func 方法版本,然后呼叫它們。
btw. template<typename T> void func(T t)
is identical to
void func(auto t)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/427998.html
