Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

template <typename  R>
struct Foo {
    R ref;
    int info;
};
class Bar {
    void* run();
}

I want to create a const variable of type foo that immediately sets the ref param as follows:

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. 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

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.

>Solution :

The solution is simple: add a deduction guide after Foo declaration:

template<typename R>
struct Foo {
    R ref;
    int info;
};

template<typename R> Foo(R, int) -> Foo<R>;

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading