为什么这些函数模板中的任何一个都与实例化不匹配?
Why don't either of these function templates match the instantiations?
以下代码无法使用英特尔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>
我哪里出错了?
在函数中使用 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"是默认模板参数。它在您的情况下不起作用,因为该功能没有过载。
相关文章:
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 将显式实例化的函数模板与转换匹配
- 函数在可变参数模板的实例化期间不可见
- 为什么我们不在下面给出的代码中使用指针来实例化C++的实体对象?
- 为什么显式模板实例化不会破坏 ODR?
- 需要实例化不同类/对象并在启动时确定的硬件插槽的设计模式
- 为什么显式模板实例化不起作用
- unique_ptr 使用尚未定义的参数进行实例化不会导致错误
- 为什么显式模板实例化不起作用?
- C++标准是否明确允许/禁止实例化不完整类型的 std::函数?
- 模板函数是否以内联方式声明 constexpr,即使实例化不是 constexpr
- 模板专用化的实例化不正确
- 完整的模板专用化不起作用:没有与指定类型匹配的函数模板"mysort2"实例 STLests
- 编译器是否也将所有参数依赖类型实例化,即使超载函数的参数计数不匹配
- 为什么很清楚模板函数实例化不会内联
- 为什么通用模板方法定义与模板类专用化不匹配?
- 为什么这些函数模板中的任何一个都与实例化不匹配?
- 模板实例化不"do inheritance"
- Wykobi -错误:显式实例化不能使用' inline '说明符[-fpermissive]