Visual Studio中嵌套模板函数的typeid不一致

Inconsistent typeid for nested template function in Visual Studio

本文关键字:函数 typeid 不一致 Studio 嵌套 Visual      更新时间:2023-10-16

在使用Visual Studio 2013 Community和2013年11月的CTP进行编译时,我在程序中偶然发现了一个奇怪的行为。下面的程序编译并打印"true",而预期的行为是打印"false",这就是GCC和clang所做的

我已经在我的设置以及以下网站上测试了此代码:http://webcompiler.cloudapp.net/(声明VS编译器版本19,也打印"true"),http://codepad.org/,http://www.tutorialspoint.com/compile_cpp_online.php,以及其他一些。

我不确定这里的正确行为是什么,也不确定下面的代码是否真的是正确的C++代码,所以我很困惑。如果有人能对这里发生的事情有所了解,那将是非常棒的。

#include <stdio.h>
#include <typeinfo>
template <typename T>
struct foo
{
    template <typename U>
    static void bar() {}
};
template <typename T>
void baz() {
    puts(typeid(&foo<T>::template bar<int>) == typeid(int) ? "true" : "false");
}
int main() {
    baz<double>();
}

编辑

多亏了Reddit,我成功地引起了STL的注意,他说他已经报告了这个错误,它将在VS 2015 RTM中修复:http://www.reddit.com/r/cpp/comments/2zs2ob/vc_2015_rtm_what_do_you_want_it_to_have/cpm01wr

VS2013(使用VS2013.4测试)确实错误地将成员函数模板的类型(static与否)指定为int。考虑下面的简化示例,其中应该很明显代码是正确的C++:

#include <typeinfo>
#include <iostream>
struct foo
{
    template<typename T>
    static void bar()
    { }
};
int main() {
    std::cout << typeid(&foo::bar<int>).name() << "n";
    std::cout << typeid(int).name() << "n";
    std::cout << (typeid(&foo::bar<int>) == typeid(int) ? "truen" : "falsen");
}

哪个将打印

int
int
true

而不是删除bar:的模板参数时会发生什么

void (__cdecl*)(void)
int
false