gpt4 book ai didi

c++ - 在 gcc 上编译代码,但不在 msvc 上编译

转载 作者:太空狗 更新时间:2023-10-29 21:48:18 24 4
gpt4 key购买 nike

我在使用 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 使用第二个类型参数时它才会失败。即使使用 -Wall -Wextra -Werror -pedantic,g++ 也能在没有警告的情况下正确编译此示例(当然,未使用的参数除外)

非常感谢。

最佳答案

嗯,我认为答案是编译器不是神写的。编译器行业的编程标准非常高,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);
}

第一次调用 Sort 失败:

cpptest1.cxx(21) : error C2664: 'THeapBasedArray::Sort' : cannot convert parameter 1 from 'int (_cdecl *)(const Item **, const Item **)' to 'int (_cdecl *)(const item_struct *, const item_struct *)

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

关于c++ - 在 gcc 上编译代码,但不在 msvc 上编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11032127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com