mardi 22 août 2017

Does captureless lambda inside template function have multiple binary implementations?

It is rather theoretical one, but my problem if lambda which is defined inside of template function, but not depend on type T nor captures anything, (so technically could be declared outside of template) is recognized and optimized out by compilers? By optimized I mean that two foo<int> and foo<double> will use same binary code of lam, so it is not duplicated. Maybe, are they required to do so by Standard? I've tried to analyse this, but only idea I came up with is try static variable inside, but it is not a miracle that lambdas for different types do not share same static variable.

// foo with helper lam which is captureless and not T-dependant
template<typename T>
int foo(T x)
{
    auto lam = [](int x) {std::cout << "foo" << std::endl;  return -x; };
    return lam(sizeof(x));
}

// foo with helper lam which is captureless and not T-dependant with static inside
template<typename T>
int foo_s(T x)
{
    auto lam = [](int x) {static int count = 0; std::cout << "foo_s " << count++ << std::endl; return -x; };
    return lam(sizeof(x));
}

int main()
{
    foo(12); // foo
    foo(12.0); // foo

    foo_s(12); // foo_s 0
    foo_s(12); // foo_s 1

    foo_s(12.0); // foo_s 0
    foo_s(12.0); // foo_s 1
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire