c++ - 在 visual studio 中使用 __LINE__ 宏作为模板参数

标签 c++ visual-studio

我希望下面的代码可以工作,但我收到了一个编译错误:

error C2975: 'n' : invalid template argument for 'foo', expected compile-time constant expression
#include <iostream>
using namespace std;

template<int N>
struct foo
{
    foo() { cout << N << endl; }
};

int main()
{
    foo< __LINE__ > f;
}

为什么会这样?我虽然 __LINE__ 会在模板实例化发生之前粘贴行号?

如果我想这样做,我应该只引入一个static const int 来保存行号还是有标准的解决方案?

最佳答案

在 VS 2010 10.0.40219.1 SP1Rel 和 Ideone 中为我工作

但是 MSDN 提到了导致 C2975 的问题,如果在带有编译器选项 /ZI 的模板中使用 __LINE__:MSDN C2975

编辑:抱歉,我链接了德语版本,here in english

关于c++ - 在 visual studio 中使用 __LINE__ 宏作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5397782/

相关文章:

android - gstreamer可以播放使用下面这个客户端代码发送的媒体内容吗?

c++ - strtok 似乎没有修改输入字符串

c++ - 使用 lambda 编译 constexpr 时出现 MSVS2017 错误 "expression did not evaluate to a constant"

c++ - 使用lambda表达式创建线程时,如何为每个线程提供自己的lambda表达式拷贝?

c++ - 如何使用 QTcpSocket 监听 qt 中的特定端口?

visual-studio - 如何安装旧版本的 Visual Studio 2017?

c# - 为什么编译器不会提示并非所有路径都返回?

c# - Response.Redirect 模式内的按钮

.net - 添加服务引用失败

c++ - 将用户值(value)与枚举中的值(value)进行比较