Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing template function instantiation in class

Tags:

c++

templates

I have a function that is declared like:

template<typename T>
void MyFunction();

And a class:

template<typename T>
class MyClass
{
public:

    typedef void (*Function_T)();
    Function_T m_Func;
    void DoSomething()
    {
        m_Func = &MyFunction<T>;
    }
}

When I use the class, I undefined symbols error on MyFunction<T>.
If I change DoSomething to

void DoSomething()
{
    m_Func = &MyFunction<T>;
    return;
    MyFunction<T>();
}

Everything works, but that looks like a workaround and will probably not work with optimization.
I cannot add

template void MyFunction<T>;

to the class because it says it cannot be in class. Is there any other way I can force instantiation of the function?

Edit:
I was able to write a test that fails, but in g++ it has a different message and actually a compiler error: http://ideone.com/RbMnh

like image 745
Dani Avatar asked Jul 21 '26 04:07

Dani


1 Answers

Your code will work with optimization as well. Although, I don't know why simply m_Func = &MyFunction<T> doesn't work. GCC 4.3.4 compiles it fine. Which compiler you're using?

And you can also do this:

void DoSomething()
{
    if ( false) MyFunction<T>();
    m_Func = &MyFunction<T>;
    return;
}

By the way, the function pointer type is incorrectly defined. It should be this:

typedef void (*Function_T)();
                     //   ^^ put this!
like image 118
Nawaz Avatar answered Jul 23 '26 19:07

Nawaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!