Lambda作为模板变量 [英] Lambda as a template variable

查看:79
本文介绍了Lambda作为模板变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在与变量模板"相关的一些调查中,我发现了一些奇怪的代码行为.标准对此行为有何说法?

During some investigation related to "Variable template" I found out some strange code behaviour for me. Does standard say anything about this behaviour?

//Header.h
#pragma once

template<typename T>
auto myvar = []() -> T&{
    static T v;
    return v;
};

//Source.cpp
#include <iostream>
#include "Header.h"

void testFunction()
{
    std::cout << myvar<int>() << '\n';
}

//main.cpp
#include <iostream>
#include "Header.h"

void testFunction();

int main(int argc, char **argv) 
{
    myvar<int>() = 10;

    testFunction();

    std::cout << myvar<int>() << '\n';
}

输出:

0
10

我希望:

10
10

推荐答案

当前,您违反了ODR:

Currently, you have ODR violation:

在两个翻译单元中,您都有(替换后)

In both translation units, you have (after substitution)

auto myvar<int> = []() -> int&{
    static int v;
    return v;
};

,但是lambda为每个TU声明一个不同的类型, 因此您将myvar<int>设置为lambda1lambda2.

but lambda declares a different type for each TU, so you have lambda1 and lambda2 for myvar<int>.

每个lambda都有其自己的static,这就是为什么您在实践中看到该结果的原因(但是程序反正格式错误,NDR).

Each lambda has its own static, that is why you see that result in practice (but program is ill-formed anyway, NDR).

这篇关于Lambda作为模板变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆