Igor
Igor

Reputation: 1059

Lambda as a template variable

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';
}

Output:

0
10

I expect:

10
10

Upvotes: 8

Views: 388

Answers (1)

Jarod42
Jarod42

Reputation: 217085

Currently, you have ODR violation:

In both translation units, you have (after substitution)

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

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

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

Upvotes: 1

Related Questions