簡體   English   中英

顯式特化“...”不是函數模板的特化

[英]explicit specialization “…” is not a specialization of a function template

我正在嘗試專門化一個函數模板,但我收到一個錯誤(標題),我不知道如何解決它。 我猜這是由於我在模板專業化中使用的混合類型。 這個想法只是在專業化中使用int作為double。 非常感謝。

template <typename T>
T test(T x) { return x*x; }

template <>
double test<int>(int x) { return test<double>(x); }

顯式特化“...”不是函數模板的特化

真正。 因為你定義了test()

template <typename T>
T test(T x) { return x*x; }

接收T類型並返回相同的 T類型。

當你定義

template <>
double test<int>(int x) { return test<double>(x); }

您正在定義一個接收int值並返回不同類型( double )的特化。

所以與T test(T)不匹配。

您可以通過重載解決問題

double test(int x) { return test<double>(x); }

正如您所說,您使用的是返回類型T = double但是對於參數T = int ,這是無效的。

你可以做的是提供一個非模板化的過載:

template<typename T>
T test(T x) { return x*x; }

// regular overload, gets chosen when you call test(10)
double test(int x) { return test<double>(x); }

當然,有人總是可以調用test<int>(/*...*/); 如果這是不可接受的,只需刪除專業化:

template<>
int test(int) = delete;

暫無
暫無

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

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