开发者

Why does this code make the VC++ compiler crash?

开发者 https://www.devze.com 2023-01-28 12:26 出处:网络
I\'m using the following compiler: Microsoft Visual C++ 2010 The following code crashes the compiler when it\'s compiled:

I'm using the following compiler:

Microsoft Visual C++ 2010

The following code crashes the compiler when it's compiled:

template<class T_> 
void crasher(T_ a, decltype(*a)* dummy = 0){}

int main()
{
    crasher(0);
    return 0;
}

decltype(*a)* used to enforce T_ to be a pointer-开发者_如何学运维like type - such as char*, int*, and shared_ptr<int>.

Why is it crashing? Is this a known bug?


Assuming your goal is

decltype(*a)* used to enforce T_ to be a pointer-like type - such as char*, int*, and shared_ptr.

... what you need is simple template, not a code which happens to crash the compiler :)

Here is something that may work for you

#include <memory>
#include <iostream>

// uncomment this "catch all" function to make select(0) compile
// int select(...){ return 0;}
template<class T>  int select(T*){ return 1;}
template<class T>  int select(std::auto_ptr<T>){ return 1;}
// add boost::shared_ptr etc, as necessary

int main()
{
    std::cout << select(0) << std::endl;
    std::cout << select(std::auto_ptr<int>()) << std::endl;
    std::cout << select(&std::cout) << std::endl;
    return 0;
}


The template isn't valid for the instantination of T_=int because prefix operator* is a substitution failure, so it should fail in some way, although without crashing of course.


I just dont understand why you write decltype(*a)* instead of decltype(a). Since 0(zero) is int by default, then the expression decltype(a) will be int as well. If you want var dummy be a pointer to decltype(a), then you have to write decltype(a)*. This way, dummy will be of type int*. You have also to consider type conversions. 0 can convert to int*. Not sure it works for all types .

0

精彩评论

暂无评论...
验证码 换一张
取 消