Специализация шаблона — компилятор не может определить тип функционального аргумента ⇐ C++
-
Гость
Специализация шаблона — компилятор не может определить тип функционального аргумента
I am trying to specialize a templated function with a functional argument, but the compiler is unable to infer the proper specialization. I get compiler errors unless I am explicit about the function type.
#include int data; using MyFunction = std::function; template void set(const T& value) { data = value; } template void set(const MyFunction& f) { data = f(); } int main() { set(1); // OK MyFunction f2 = []() { return 1; }; // OK set(f2); auto f1 = []() { return 1; }; // COMPILE ERROR set(f1); set([]() { return 1; }); // COMPILE ERROR return 0; } The compiler error (g++/c++11):
main.cpp: In instantiation of ‘void set(const T&) [with T = main()::]’: main.cpp:26:8: required from here main.cpp:10:10: error: invalid user-defined conversion from ‘const main()::’ to ‘int’ [-fpermissive] 10 | data = value; | ~~~~~^~~~~~~ main.cpp:25:15: note: candidate is: ‘constexpr main()::::operator int (*)()() const’ (near match) 25 | auto f1 = []() { return 1; }; // COMPILE ERROR Example code includes a boiled-down version of my attempts. Tried C++11, 14, 17, 20 with same results. MSVC 16 and g++, similar results.
I'm hoping/expecting the compiler to correctly infer the lambda function type and pick the correct specialization.
Источник: https://stackoverflow.com/questions/781 ... ument-type
I am trying to specialize a templated function with a functional argument, but the compiler is unable to infer the proper specialization. I get compiler errors unless I am explicit about the function type.
#include int data; using MyFunction = std::function; template void set(const T& value) { data = value; } template void set(const MyFunction& f) { data = f(); } int main() { set(1); // OK MyFunction f2 = []() { return 1; }; // OK set(f2); auto f1 = []() { return 1; }; // COMPILE ERROR set(f1); set([]() { return 1; }); // COMPILE ERROR return 0; } The compiler error (g++/c++11):
main.cpp: In instantiation of ‘void set(const T&) [with T = main()::]’: main.cpp:26:8: required from here main.cpp:10:10: error: invalid user-defined conversion from ‘const main()::’ to ‘int’ [-fpermissive] 10 | data = value; | ~~~~~^~~~~~~ main.cpp:25:15: note: candidate is: ‘constexpr main()::::operator int (*)()() const’ (near match) 25 | auto f1 = []() { return 1; }; // COMPILE ERROR Example code includes a boiled-down version of my attempts. Tried C++11, 14, 17, 20 with same results. MSVC 16 and g++, similar results.
I'm hoping/expecting the compiler to correctly infer the lambda function type and pick the correct specialization.
Источник: https://stackoverflow.com/questions/781 ... ument-type
Мобильная версия