【发布时间】:2024-04-27 02:45:02
【问题描述】:
我在使用 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++ 也可以正确编译此示例而不会出现警告(当然,未使用的参数除外)
非常感谢。
【问题讨论】:
-
我的猜测是 MSVC 期望
typename引入类型参数,但这里Ptr是非类型参数。不过,模板参数的语法并不方便。 -
好主意,但不幸的是它似乎与此无关。有一个错误甚至暗示应该使用 typename 关键字。这对我来说确实有意义,因为 T* 确实是一种类型。
-
我会让情况更糟:这也不起作用://适用的变体 template
void callFun() { callFun2 (); }
标签: c++ templates g++ visual-c++-2010 visual-studio-2010