我刚刚遇到了 MSVC(版本 12 更新 5)的问题:
如果模板函数具有通过 SFINAE 禁用的重载,则显式实例化模板函数会失败。但是,调用该函数(从而隐式实例化它)是有效的。
示例代码:
#include <type_traits>
template <typename T>
std::enable_if_t< std::is_integral<T>::value, // test is true for T=int
void> foo( T& ) {}
template <typename T>
std::enable_if_t< std::is_pointer<T>::value, // test is false for T=int
void> foo( T& ) {}
void bar( )
{
int i;
foo( i ); // calls foo( int& ) (obviously), compiles fine
}
template void foo( int& ); // explicit instantiation, throws compiler error
我得到的编译器错误是error C2794: 'type' : is not a member of any direct or indirect base class of 'std::enable_if<false,void>'
。
相同的代码对于 GCC 来说似乎没问题(除了缺少 main 函数):住在 Ideone 上 http://ideone.com/K6ro4u.
这是 MSVC 错误吗?有没有好的方法来进行这些显式模板实例化?
以下允许实例化该函数,确保它可以编译并且应该(根据我的理解)将其放入 .obj 文件中:
namespace {
template <typename T>
void helper( T& A )
{
foo( A );
}
template void helper( int& );
}
这里的技巧是,helper(..)
既不过载,也不禁用任何类型。排序禁用的重载被延迟到“调用”foo(..)
within helper(..)
,MSVC 成功解决了这个问题。
编辑:
正如我们所看到的,其他编译器理解我的原始代码以及较新版本的 MSVC(感谢 Niall),我认为这是我的 MSVC 版本的错误,并充分考虑了该部分问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)