Мне не удалось сохранить std::function<>
как generic lambda
в классе напрямую как member
. Что я смог сделать, так это специально использовать его в конструкторе класса. Я не уверен на 100%, что это то, чего пытался достичь ОП, но это то, что я смог скомпилировать, построить и запустить с тем, к чему, как я подозреваю, стремился ОП с помощью предоставленного ими кода.
template<class>
class test {
public: // While testing I changed this to public access...
// Could not get object below to compile, build & run
/*template<class U = T>
static std::function<void(U)> fooCall;*/
public:
test();
};
template<class T>
test<T>::test() {
// This would not compile, build & run
// fooCall<T> = []( T t ) { std::cout << t.sayHello(); };
// Removed the variable within the class as a member and moved it here
// to local scope of the class's constructor
std::function<void(T)> fooCall = []( auto a ) { std::cout << a.sayHello(); };
T t; // created an instance of <Type T>
fooCall(t); // passed t into fooCall's constructor to invoke the call.
}
struct A {
std::string sayHello() { return "A say's Hello!\n"; }
};
struct B {
std::string sayHello() { return "B say's Hello!\n"; }
};
int main() {
// could not instantiate an object of SomeClass<T> with a member of
// a std::function<> type that is stored by a type of a generic lambda.
/*SomeClass<A> someA;
SomeClass<B> someB;
someA.foo();
someB.foo();*/
// Simply just used the object's constructors to invoke the locally stored lambda within the class's constructor.
test<A> a;
test<B> b;
std::cout << "\nPress any key & enter to quit." << std::endl;
char c;
std::cin >> c;
return 0;
}
С соответствующими заголовками приведенное выше, как есть, должно компилироваться, собираться и запускаться, давая приведенный ниже вывод (по крайней мере, в MSVS 2017 на 64-разрядной версии Windows 7); Я оставил комментарии, где столкнулся с ошибками и попробовал несколько разных методов для получения рабочего примера, ошибки возникали, как предлагали другие, и я обнаружил еще больше, работая с приведенным выше кодом. То, что я смог скомпилировать, построить и запустить, сводилось к этому простому фрагменту кода без комментариев. Я также добавил еще один простой класс, чтобы показать, что он будет работать с любым типом:
template<class>
class test {
public:
test();
};
template<class T>
test<T>::test() {
std::function<void( T )> fooCall = []( auto a ) { std::cout << a.sayHello(); };
T t;
fooCall( t );
}
struct A {
std::string sayHello() { return "A say's Hello!\n"; }
};
struct B {
std::string sayHello() { return "B say's Hello!\n"; }
};
struct C {
int sayHello() { return 100; }
};
int main() {
test<A> testA;
test<B> testB;
test<C> testC;
std::cout << "\nPress any key & enter to quit." << std::endl;
char c;
std::cin >> c;
return 0;
}
Выход:
A say's Hello!
B say's Hello!
100
Press any key & enter to quit
Я не знаю, поможет ли это ОП прямо или косвенно или нет, но если это так или даже если это не так, это все равно то, к чему они могут вернуться и от чего отталкиваться.
person
Francis Cugler
schedule
18.11.2017