MSVC:显式模板实例化失败而隐式实例化成功 [英] MSVC: explicit template instantiation fails while implicit instantiation succeeds

查看:28
本文介绍了MSVC:显式模板实例化失败而隐式实例化成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚遇到了 MSVC(版本 12 更新 5)的问题:

I just came across a problem with MSVC (Version 12 Update 5):

显式实例化模板函数失败,如果该函数具有通过 SFINAE 禁用的重载.但是,调用该函数(从而隐式实例化它)是有效的.

Explicitly instantiating a template function fails, if that function has an overload which is disabled through SFINAE. However, calling that function (thereby implicity instantiating it) works.

示例代码:

#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' : 不是 'std::enable_if<false,void>' 的任何直接或间接基类的成员.相同的代码似乎适用于 GCC(除了缺少主要功能):在 Ideone 上直播.

The compiler error I get is error C2794: 'type' : is not a member of any direct or indirect base class of 'std::enable_if<false,void>'. The same code seems to be fine with GCC (apart from missing the main function): live on Ideone.

这是一个 MSVC 错误吗?有没有什么好的方法可以让这些显式的模板实例化?

Is this an MSVC bug? Is there a good way to make these explicit template instantiations?

推荐答案

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

The following allows to instantiate the function, making sure it compiles and should (by my understanding) also put it into the .obj-file:

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

  template void helper( int& );
}

这里的诀窍是,helper(..) 既不超载,也不禁用任何类型.整理禁用的重载延迟到 helper(..) 内对 foo(..) 的调用",MSVC 成功解决了该问题.

The trick here is, that helper(..) is neither overloadad, nor disabled for any type. Sorting out the disabled overloads is delayed to the 'call' to foo(..) within helper(..), which MSVC succeeds to resolve.

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

As we have seen that other compilers understand my original code, as well as newer versions of MSVC (thanks Niall), I assume it is a bug of my version of MSVC, and consider that part question sufficiently thought over.

这篇关于MSVC:显式模板实例化失败而隐式实例化成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆