我遇到了關於enable_if和模板特化的正確使用的問題。模板特化和enable_if問題
修改的例子(出於保密原因)後,這裏有一個可比的例子:
I have function called "less" that checks if 1st arg is less than 2nd arg. Let's say I want to have 2 different kinds of implementations depending on the type of input - 1 implementation for integer and another for double.
,我至今看起來像這樣的代碼 -
#include <type_traits>
#include <iostream>
template <class T,
class = typename std::enable_if<std::is_floating_point<T>::value>::type>
bool less(T a, T b) {
// ....
}
template <class T,
class = typename std::enable_if<std::is_integral<T>::value>::type>
bool less(T a, T b) {
// ....
}
int main() {
float a;
float b;
less(a,b);
return 0;
}
上面的代碼無法編譯因爲 - 它說我正在重新定義更少的方法。
錯誤是:
Z.cpp:15:19: error: template parameter redefines default argument
class = typename std::enable_if<std::is_integral<T>::value>::type>
^
Z.cpp:9:19: note: previous default template argument defined here
class = typename std::enable_if<std::is_floating_point<T>::value>::type>
^
Z.cpp:16:11: error: redefinition of 'less'
bool less(T a, T b) {
^
Z.cpp:10:11: note: previous definition is here
bool less(T a, T b) {
^
Z.cpp:23:5: error: no matching function for call to 'less'
less(a,b);
^~~~
Z.cpp:15:43: note: candidate template ignored: disabled by 'enable_if'
[with T = float]
class = typename std::enable_if<std::is_integral<T>::value>::type>
^
3 errors generated.
有人能說出什麼是錯在這裏?
基本上,由於您如何調用返回類型,您並未正確使用'enable_if'。 – Alex
快速解決方案是將一個省略號參數'...'添加到其中一個模板,以便將它們視爲不同的重載。 – 0x499602D2
或將簽名更改爲'template :: value> :: type * = nullptr>' –
vsoftco