Home > Enterprise >  How can I define a static templated variable without knowing the template data type?
How can I define a static templated variable without knowing the template data type?

Time:01-09

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.

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.

CodePudding user response:

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

  • Related