gpt4 book ai didi

c++ - MSVC : explicit template instantiation fails while implicit instantiation succeeds

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:21:48 38 4
gpt4 key购买 nike

我刚遇到 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(除了缺少主要功能):live on Ideone .

这是 MSVC 错误吗?有没有好的方法来进行这些显式模板实例化?

最佳答案

下面允许实例化函数,确保它编译并且应该(据我理解)也将它放入 .obj 文件中:

namespace {
template <typename T>
void helper( T& A )
{
foo( A );
}

template void helper( int& );
}

这里的技巧是,helper(..) 既没有过载,也没有为任何类型禁用。对禁用的重载进行分类被延迟到 helper(..) 中对 foo(..) 的“调用”,MSVC 成功解决了这一问题。

编辑:正如我们所看到的,其他编译器理解我的原始代码以及更新版本的 MSVC(感谢 Niall),我认为这是我的 MSVC 版本的错误,并充分考虑了这部分问题。

关于c++ - MSVC : explicit template instantiation fails while implicit instantiation succeeds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38952448/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com