Fel*_*nto 3 c++ pointers function c++11
如何在不保存返回类型的情况下保存指向函数的指针?
例如:
int GetInt() { return 5; }
string GetStr() { return "abc"; }
FunctionPointerClass GetAny;
int main()
{
GetAny = &GetInt;
auto var = GetAny();
GetAny = &GetStr;
auto var2 = GetAny();
cout << var << '\n' << var2;
}
Run Code Online (Sandbox Code Playgroud)
一个简单的方法是使用variant<>
(感谢@sehe),如下所示:
#include <boost/variant.hpp>
#include <string>
#include <iostream>
#include <functional>
int GetInt() { return 5; }
std::string GetStr() { return "abc"; }
int main()
{
std::function<boost::variant<int, std::string>()> Get;
Get = &GetInt;
std::cout << Get() << '\n';
Get = &GetStr;
std::cout << Get() << '\n';
}
Run Code Online (Sandbox Code Playgroud)
但是,它不太适用于我的项目:非类型的类.要使用它,我将需要堆栈所有使用的返回类型,将其放在模板中variant<>
.像这样:
class Var {
private:
void* _val;
template <typename T>
T& _Get() const {
return *((T*)_val);
}
// Static stack variable HERE
public:
val() {}
template <typename T>
val(T val) {
Set(val);
}
~val() {
if(_val != nullptr) delete _val;
}
std::function<boost::variant</*Stack*/>()> Get;
template <typename T>
void Set(T val) {
if(_val != nullptr) delete _val;
_val = new T(val);
Get = &_Get<T>;
// TODO Add 'T' to Stack
}
};
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
不完全是.
您当然可以使其成为打印值的功能.
或者您可以使用std::variant
/ boost::variant
返回任一类型.
其他技术,如Type Erasure也可能适用.
我在这里充实了最后两种方法:
variant<>
#include <boost/variant.hpp>
#include <string>
#include <iostream>
#include <functional>
int GetInt() { return 5; }
std::string GetStr() { return "abc"; }
int main()
{
std::function<boost::variant<int, std::string>()> Get;
Get = &GetInt;
std::cout << Get() << '\n';
Get = &GetStr;
std::cout << Get() << '\n';
}
Run Code Online (Sandbox Code Playgroud)
打印
5
abc
Run Code Online (Sandbox Code Playgroud)
相关技术是类型擦除,您可以使用支持的操作(在本例中为输出流)定义"概念",并将其隐藏在多态接口后面.例如:
struct Printable {
template <typename T> Printable(T v) : _stored(new concrete<T>(v)) { }
friend std::ostream& operator<<(std::ostream& os, Printable const& p) {
return p._stored->print(os);
}
private:
struct interface {
virtual std::ostream& print(std::ostream& os) const = 0;
virtual ~interface() = default;
};
template <typename T>
struct concrete : interface {
concrete(T v) : v(v) {}
virtual std::ostream& print(std::ostream& os) const override {
return os << v;
}
T v;
};
std::unique_ptr<interface> _stored;
};
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您可以制作整个程序:
int GetInt() { return 5; }
std::string GetStr() { return "abc"; }
int main()
{
std::function<Printable()> Get;
Get = &GetInt;
std::cout << Get() << '\n';
Get = &GetStr;
std::cout << Get() << '\n';
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
93 次 |
最近记录: |