我可以使用enable_if来具有名称相同,参数相同但返回类型不同的两个函数吗?

时间:2018-12-21 14:53:21

标签: c++ templates enable-if

根据this post,enable_if可用于定义两个具有相同名称,相同参数但返回类型不同的函数。

但是,当我这样做时:

#include <type_traits>

template <typename T,
          typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
T f1() {
  // T double, float...
}

template <typename T,
          typename = typename std::enable_if<!std::is_floating_point<T>::value>::type>
T f1() {
  // T is something else
}

int main( int argc, char* argv[] )
{
    auto res1 = f1<float>();

    auto res2 = f1<int>();

    return 0;
}

我收到一个错误报告f1,它定义了两次:

11:3: error: redefinition of 'template<class T, class> T f1()'
5:3: note: 'template<class T, class> T f1()' previously declared here
 In function 'int main(int, char**)':
19:25: error: no matching function for call to 'f1()'
19:25: note: candidate is:
5:3: note: template<class T, class> T f1()
5:3: note:   template argument deduction/substitution failed:
4:11: error: no type named 'type' in 'struct std::enable_if<false, void>'
17:10: warning: unused variable 'res1' [-Wunused-variable]
 In instantiation of 'T f1() [with T = float; <template-parameter-1-2> = void]':
17:27:   required from here
7:1: warning: no return statement in function returning non-void [-Wreturn-type]

请参见http://cpp.sh/3g2vy

这应该起作用吗?我在做什么错了?

0 个答案:

没有答案