在 gcc 上编译代码,但不在 msvc 上编译代码
Code compiling on gcc, but not on msvc
我在使用 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 *)
而第二个调用编译器很好。对我来说,这是编译器中的一个错误。有时会发生这种情况。我想这就是答案。
相关文章:
- 在Linux for Windows上编译C++代码时出错
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在程序中编写脚本来编写和编译代码
- 未定义的引用 .. 使用 OpenCV 编译 C++ 代码时,从命令行
- 在macos上编译代码的未解析符号
- 使用个人C++库编译代码时,与头文件一起使用时会中断
- 使用指针编译代码后,.cpp文件将变为随机字符
- VS Express 无法正确编译代码(?
- 如何在Ubuntu中使用Visual Studio代码编译C++代码
- 使用 Android NDK 使用 clang++ 编译C++代码时对"_Unwind_Resume"的未定义引用
- 无法使用两个包装不同下一层的ssl_stream编译代码
- 编译代码时"[Warning] extra tokens at end of"
- 无法编译代码,因为它已在 C++11 中弃用
- 如何在 Azure 应用服务中使用 cl.exe 编译 C++ 代码并生成可执行文件
- 如何调试编译 c++ 代码的 bazel?
- 为什么在使用转换构造函数编译代码时需要 const 复制构造函数?
- 编译 C++ 代码后尺寸较大
- 使用用 C++ 和 DDS 编写的 CMAKE 编译代码
- 编译代码时如何不制作二进制文件?
- 如何使用所有其他文件信息来编译代码,例如HAAR级联训练的权重的XML文件