Why can't the compiler deduce auto template parameter unless I add const?

时间:2017-12-18 07:25:35

标签: c++ templates language-lawyer c++17 argument-deduction

I recently had problem with code like this:

constexpr auto lambda = []{};

template<auto& l>
struct Lambda {};

template<auto& l>
void test(Lambda<l>) {}

int main() {
    test(Lambda<lambda>{});
}

Both clang and GCC tells that it can't deduce l.

However, if I add const there:

//   ----v
template<const auto& l>
void test(Lambda<l>) {}

Then everything works with clang. GCC still fails. What's happening here? Can it not deduce the const itself? Is this a GCC bug for it to not deducing l in both cases?

1 个答案:

答案 0 :(得分:8)

Is this a GCC bug for it to not deducing l in both cases?

It is a bug, and for Clang too. For a placeholder type non-type argument, [temp.arg.nontype]/1 says:

If the type of a template-parameter contains a placeholder type, the deduced parameter type is determined from the type of the template-argument by placeholder type deduction. If a deduced parameter type is not permitted for a template-parameter declaration ([temp.param]), the program is ill-formed.

The very same process by which it would deduce here

setTimeout(function a (b){
   element.classList.add('classNameA');
},200);

function b () {
   element.classList.add('classNameB');
}

That int main() { auto& l = lambda; } is const reference.