Is it possible to edit template name at compile time? [closed]
I am trying to modify template type given at compile time but unable to do it. Let see if you have some idea.
Lets consider we have 2 classes class A and A_test and one template class B. Will implemented class B as it is having a function b_f() which is internaly creating an object of template class and calling public funcion A_f()/A_test_f() of class A or Class A_test.
from main, will be creating class B obj; obj.b_f(); but I want to creat an object of class A_test not class A.
Let me know if it is possible.
Basicaly I wanted to do object injection. Please let me know if it is possible.
The best solution by far is to try to rename A_test_f() to be the same as A_f().
If that proves impossible, the next thing I'd try is to specialize class B:
template<class AT>
class B {
public: b_f() {
AT m_A;
m_A.A_f();
};
template<>
class B<A_test> {
public: b_f() {
AT m_A;
m_A.A_test_f();
};
If B
is too complicated, there are other things to try, but you probably want to rethink what you're doing first. If all else fails, do what I coded above here, but call it B_HELPER
instead of B
and then b_f() can do: B_HELPER<AT> m_A; m_A.b_f();
That way you don't have to recode all of B
.
The common way to inject dependencies into templates at compile-time is through type traits. This allows customizing the templates externally through another struct or class which has specific knowledge of the class. Examples in the standard library include std::char_traits<>
and std::iterator_traits<>
. Boost also defines some, including boost::type_traits<>
.
Traits involve defining a struct for the general case and specializing it for alternate cases when necessary.
// general case: select method named "f".
template<class T> struct b_traits
{
typedef void(T*F)();
static const F f = &T::f;
};
// template type that forwards method selection to "b_traits" struct.
template<class AT>
class B {
public: b_f() {
AT m_A;
(m_A.*(b_traits<AT>::f))();
};
class A_test { ... };
// special case: select method named "A_test_f".
template<> struct b_traits<A_test>
{
typedef void(T*F)();
static const F f = &A_test::A_test_f;
};
int main ()
{
B<A_test> b;
b.b_f(); // will invoke "A_test::A_test_f()" rather than "A_test::f()".
}
精彩评论