[英]Code compiling on gcc, but not on msvc
I have a problem compiling a template using msvc-2010. 我在使用msvc-2010编译模板时遇到问题。 It works perfectly using gcc 4.6.3. 它使用gcc 4.6.3完美运行。
I have boiled down the code to the essential (it doesn't make sense of course): 我把代码归结为必要的(当然没有意义):
//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;
}
The Error: 错误:
error C2975: 'Ptr' : invalid template argument for 'callFun2', expected compile-time constant expression
I find it interesting, that it only fails when the second type parameter is being used through a typedef in a Traits class. 我发现它很有趣,它只在通过Traits类中的typedef使用第二个类型参数时才会失败。 g++ compiles this example correctly without warnings, even when using -Wall -Wextra -Werror -pedantic (Except for the unused parameters, of course) g ++正确编译此示例而没有警告,即使使用-Wall -Wextra -Werror -pedantic(当然,除了未使用的参数)
Thank you very much. 非常感谢你。
Well, I think that the answer is that compilers are not written by gods. 嗯,我认为答案是编译器不是由神写的。 Programming standards in the compiler industry are extremely high, MS C++ is a good compiler, but it still contain bugs. 编译器行业的编程标准非常高,MS C ++是一个很好的编译器,但它仍然包含bug。 I came across the following, that is somehow similar to what you are pointing at: 我遇到了以下内容,这与您指向的内容类似:
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);
}
The first call to Sort fails with: 对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 *) cpptest1.cxx(21):错误C2664:'THeapBasedArray :: Sort':无法将参数1从'int(_ cdecl *)(const Item **,const Item **)'转换为'int( _cdecl *)(const item_struct *,const item_struct *)
while the second call compilers fine. 而第二次调用编译器很好。 For me this is a bug in a compiler. 对我来说,这是编译器中的一个错误。 Sometimes this happens. 有时这会发生。 I guess this is the answer. 我想这就是答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.