在 gcc 上编译代码,但不在 msvc 上编译代码

Code compiling on gcc, but not on msvc

本文关键字:编译 代码 msvc gcc      更新时间:2023-10-16

我在使用 msvc-2010 编译模板时遇到问题。它使用 gcc 4.6.3 完美运行。

我已经将代码归结为基本代码(当然没有意义):

//Variant that works
template <typename T, T* Ptr>
void callFun()
{
}
//Traits class (type expands to the same type T* as above)
template <typename T>
class TraitsClass
{
public:
    typedef T* type;
};
//Essentially the same as callFun2, only that the
//type of Ptr is expressed indirectly over a traits class
//The usage of this class is not possible, because of the error described below
template <typename T, typename TraitsClass<T>::type Ptr>
void callFun2()
{
}
//Provides a compile constant ptr for this example
void testFun()
{
}
int main()
{
    //Works
    callFun<void(), &testFun>();
    //Fails
    callFun2<void(), &testFun>();
    //Works
    callFun2<void(), 0>();
    return 0;
}

错误:

error C2975: 'Ptr' : invalid template argument for 'callFun2', expected compile-time constant expression

我觉得有趣的是,它仅在通过 Traits 类中的 typedef 使用第二个类型参数时才失败。g++ 在没有警告的情况下正确编译此示例,即使使用 -Wall -Wextra -Werror -pedantic (当然,未使用的参数除外)

谢谢。

好吧,我认为答案是编译器不是由上帝编写的。编译器行业的编程标准非常高,MS C++是一个很好的编译器,但它仍然包含错误。我遇到了以下内容,这与您所指的内容有些相似:

template <class item_struct>
struct THeapBasedArray
{
    void  Sort(int (__cdecl *compareFunction)(const item_struct *item1,
                                              const item_struct *item2));
};
struct Item { int x; };
struct ItemPtrsArray : public THeapBasedArray<Item*>
{
    static int __cdecl  Compare1(const Item **pp1, const Item **pp2);
    typedef Item *ItemPtr;
    static int __cdecl  Compare2(const ItemPtr *pp1, const ItemPtr *pp2);
};
int main()
{
    ItemPtrsArray vect;
    vect.Sort(ItemPtrsArray::Compare1);
    vect.Sort(ItemPtrsArray::Compare2);
}

对排序的第一次调用失败,并显示:

cpptest1.cxx(21):错误 C2664: 'THeapBasedArray::Sort' : 无法将参数 1 从 'int (_cdecl *)(const Item **, const Item **)' 转换为 'int (_cdecl *)(const item_struct *, const item_struct *)

而第二个调用编译器很好。对我来说,这是编译器中的一个错误。有时会发生这种情况。我想这就是答案。