【问题标题】:passing reference of a variable to a template将变量的引用传递给模板
【发布时间】:2016-02-16 21:15:08
【问题描述】:

我正在尝试使用以下代码将引用变量传递给模板,但出现编译器错误。请问哪位大神能说说原因。谢谢。

#include<iostream>
using namespace std;

template<int &T>
class Test
{
public:
    static void do_it()
    {
        T=1;
    }
};

struct A{
    static int x;
};

int A::x=0;

int main()
{
    Test<A::x> test;
    test.do_it();
    cout<<A::x;
    return 0;
}

错误:

错误 C2143:语法错误:在 '.' 之前缺少 ','
错误 C2143:语法错误:缺少“;”在'}'之前
错误 C2143:语法错误:缺少“;”在'}'之前
致命错误 C1004:发现意外的文件结尾

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    Test&lt;A.x&gt; test; 应该是Test&lt;A::x&gt; test;

    【讨论】:

    • 非常感谢,有什么具体原因,为什么它只允许传递静态成员而不是普通数据成员?
    • @Raj,我猜是因为你使用非类型参数,参数应该在编译时知道。但我不太确定。
    猜你喜欢
    • 2017-11-10
    • 2019-04-03
    • 2011-05-08
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 2018-06-20
    • 1970-01-01
    相关资源
    最近更新 更多