正向宣称使用enable_if功能:通话暧昧
-
19-09-2019 - |
题
我有些麻烦向前宣称使用 boost::enable_if
的函数:下面的码片给我一个编译器错误:
// Declaration
template <typename T>
void foo(T t);
// Definition
template <typename T>
typename boost::enable_if<boost::is_same<T, int> >::type foo(T t)
{
}
int main()
{
foo(12);
return 0;
}
编译时,我得到一个“暧昧调用foo”的错误。据enable_if
的定义,“类型”的typedef相当于void
当条件为真,那么据我所看到的,foo
比赛的两个签名。为什么编译器认为它们是不同的,并且在那里转发声明foo
(优选不重复enable_if
一部分)以正确的方式?
解决方案
此不仅与enable_if的问题。你得到的Visual Studio和GCC与下面的代码相同的错误:
struct TypeVoid {
typedef void type;
};
template<typename T>
void f();
template<typename T>
typename T::type f() {
}
int main()
{
f<TypeVoid>();
return 0;
}
我认为主要问题是,返回类型(实例化之前)是一个模板函数的签名的一部分。有更多的信息此处。
关于你的代码,如果该声明是指定义,你应该同时匹配:
// Declaration
template <typename T>
typename boost::enable_if<boost::is_same<T, int> >::type foo(T t);
// Definition
template <typename T>
typename boost::enable_if<boost::is_same<T, int> >::type foo(T t)
{
}
如果该声明是指不同的函数,编译器将永远无法选择正确的一个的 INT 的S,因为它们都是有效的。但是,可以禁用第一一个用于 INT S使用的 disable_if :
// Other function declaration
template <typename T>
typename boost::disable_if<boost::is_same<T, int> >::type foo(T t);
// Defition
template <typename T>
typename boost::enable_if<boost::is_same<T, int> >::type foo(T t)
{
}
其他提示
的问题是,该声明和定义不匹配。
的解决方案是,该声明应包含完全相同的签名,和所述enable_if
位。
#include <boost/type_traits/is_same.hpp>
#include <boost/utility/enable_if.hpp>
// Declaration
template <typename T>
typename boost::enable_if<boost::is_same<T, int> >::type foo(T t);
// Definition
template <typename T>
typename boost::enable_if<boost::is_same<T, int> >::type foo(T t)
{
}
int main()
{
foo(12);
return 0;
}
此编译罚款上VC2008。
不隶属于 StackOverflow