【问题标题】:Why don't either of these function templates match the instantiations?为什么这些函数模板都不匹配实例化?
【发布时间】:2012-10-02 12:52:17
【问题描述】:

以下代码无法使用 Intel C++ 2013 编译。

#include <type_traits>
#include <iostream>


template <
    typename T, 
    typename std::enable_if<std::is_integral<T>::value>::type
>
void myfunc( T a) 
{ 
    std::cout << a << std::endl;
}

template <
    typename T, 
    typename std::enable_if<!std::is_integral<T>::value>::type
>
void myfunc( T a) 
{ 
    std::cout << a << std::endl;
}




int main()
{
    double a;
    int b;
    myfunc(a);
    myfunc(b);

    return 0;

}

这是错误输出:

ConsoleApplication1.cpp(33): error : no instance of overloaded function "myfunc" matches the argument list
1>              argument types are: (double)
1>      myfunc(a);
1>      ^
1>  
1>ConsoleApplication1.cpp(34): error : no instance of overloaded function "myfunc" matches the argument list
1>              argument types are: (int)
1>      myfunc(b);
1>      ^
1>  

我哪里错了?

【问题讨论】:

  • std::cout &lt;&lt; T?你的意思是a
  • 您不能有 void 类型的模板非类型参数。告诉 enable_if 给你一个 int 类型并提供一个默认值

标签: c++ templates c++11 sfinae enable-if


【解决方案1】:

在函数中使用enable_if 的通常且正确的方法是将其粘贴在返回类型中。

template <typename T>
typename std::enable_if<std::is_integral<T>::value>::type myfunc(T a) {
    std::cout << a << " (integral)" << std::endl;
}

template <typename T>
typename std::enable_if<!std::is_integral<T>::value>::type myfunc(T a) {
    std::cout << a << " (non-integral)" << std::endl;
}

对于您的变体,正确的方法是:

template <typename T,
          typename = typename std::enable_if<std::is_integral<T>::value>::type>
void myfunc(T a) {
    std::cout << a << " (integral)" << std::endl;
}

...“enable_if”是一个默认模板参数。它不适用于您的情况,因为该函数没有重载。

【讨论】:

  • 谢谢,我知道它的使用频率更高,但是我使用的变体(或者至少是它的正确版本!)也是可以接受的,我想在这种情况下使用 void 函数.
  • @JoshGreifer enable_if 省略的第二个参数默认为void。此答案中的myfuncs 不需要返回任何值,返回类型为void
  • 好吧,我想我明白了——所以如果我想让 myfuncs 返回 int,我可以使用 std::enable_if&lt;!std::is_integral&lt;T&gt;::value, int&gt;::type ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-20
  • 2014-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多