[英]How can I define a static templated variable without knowing the template data type?
Let's say I have the following struct to store a reference to a class member variable:假设我有以下结构来存储对 class 成员变量的引用:
template <typename R>
struct Foo {
R ref;
int info;
};
class Bar {
public:
void* run();
};
I want to create a const variable of type foo that immediately sets the ref param as follows:我想创建一个 foo 类型的 const 变量,它立即设置 ref 参数如下:
const Foo theVar {&Bar::run, 0x1000}; //Doesn't work, but preferred
const Foo<void (Bar::*)()> theVar {&Bar::run, 0x1000}; //Does work, but rather not
The reason I'm using a template in this case is because there's no way to cast a class member variable to a void*
, so I'm forced into this position. However, it seems that I cannot declare the variable without first telling the compiler what type I'm planning to use.我在这种情况下使用模板的原因是因为没有办法将 class 成员变量转换为
void*
,所以我被迫进入这个 position。但是,似乎我不能在没有先告诉编译器我打算使用什么类型。 Although I do have this information, it's not the prettiest way to accomplish what I want and could possibly cause some issues in the long run.虽然我确实有这些信息,但这不是完成我想要的事情的最好方法,从长远来看可能会导致一些问题。
The compiler should be able to tell that I'm passing a variable of type void (Bar::*)()
to this struct, so I'm almost certain there has to be a way around this issue.编译器应该能够告诉我正在将类型为
void (Bar::*)()
的变量传递给此结构,因此我几乎可以肯定必须有解决此问题的方法。
The reason I'm in need of this struct is because I need a reference to exist for the linker. I don't want it to be set on run-time, it needs to be available for the linker. Using templates seems to be the only way to accomplish this.我需要这个结构的原因是因为我需要 linker 的引用。我不希望它在运行时设置,它需要对 linker 可用。使用模板似乎是实现这一目标的唯一途径。
The solution is simple: add a deduction guide after Foo
declaration:解决方法很简单:在
Foo
声明后添加推导指南:
template<typename R>
struct Foo {
R ref;
int info;
};
template<typename R> Foo(R, int) -> Foo<R>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.