Template type inference according to constructor argument

I have a class template, the constructor of which takes the called, whose type is a template parameter. I would like this type to be inferred, so I don't need to specify it whenever an instance of the class.

Unfortunately, type deduction does not work in the example below. Is there any way to make it work?

template<typename F> class C { public: C(F&& f) : m_f{f} {} private: F m_f; }; class D { public: static int s() { return 0; } private: C<decltype(&s)> c {&s}; // OK C<> c2 {&s}; // error, not enough template parameters }; 

https://wandbox.org/permlink/8cphYR7lCvBA8ro4

Note that this is similar to Can I use template parameter output in class data elements? but here I am asking for something similar to work, not standard compliance.

Another remark is that when re-describing the type of the template parameter in the above example, this is simply an unsatisfactory inconvenience (which of the answers below suggests solving with a macro), I'm not sure how to do this, you could have an instance of C with F as non-global type of lambda function (for example, one that is defined locally) if this instance is a data member. A technique that would allow this to be very powerful and useful, IMHO.

+5
source share
2 answers

If your main goal is not to print &s twice, a pragmatic solution is to define a macro:

 #define CC(name,value) decltype(C{value}) name{value} class D { public: static int s() { return 0; } private: CC(c,&s); // lambda still not possible: // CC(c2,[](){return 42;}); }; 
+4
source

You can do something like this:

 decltype(C{&s}) c{&s}; 

But I do not know how to avoid duplication &s .

+3
source

Source: https://habr.com/ru/post/1276064/


All Articles