MSVC编译失败,显式可变模板函数实例化

时间:2019-07-04 22:51:29

标签: c++ visual-c++ sfinae forward-declaration internal-compiler-error

我将问题简化为一个小例子,请原谅宏。在this帖子中似乎有类似的问题在VS中不再是问题,并且可以正常编译。我相信我对此问题有一个更专业的版本,但尚未解决,但想确保我没有遗漏任何东西。以下代码在GCC中编译并可以正常运行,但是在VS中给出了错误C2893(无法专门化功能模板):

Macros.h:

#define If(x) \
  template<class T,class...Args, typename std::enable_if<std::is_same<T, x>::value>::type* = nullptr>
#define Do void Func(Args... args)

Definition.cpp:

#include <string>
#include <iostream>
#include "Macros.h"
using namespace std;


int answer  = 42;
double pie  = 3.14;
string s    = "Hello World";

// Function Definitions
If(int)    Do { cout << answer << endl; }
If(double) Do { cout << pie << endl; }
If(string) Do { cout << s << endl; }

// Explicit Instantiations
template void Func<int>(int, double, string);
template void Func<double>();
template void Func<string>();

Usage.cpp:

#include <string>
#include <type_traits>
#include "Macros.h"

// Template Function Declaration
If(T) Do;

int main() {
    using namespace std;
    Func<int>(5, 2.0, string("hello"));
    Func<double>();
    Func<string>();
}

与其他文章中的示例一样,如果实例化来自函数的实际使用,则它可以正常工作。在这个示例中,这样做很简单,但是对于我的代码而言,却并非如此。

0 个答案:

没有答案