在类中强制模板函数实例化

时间:2011-09-01 17:19:15

标签: c++ templates

我有一个声明如下的函数:

template<typename T>
void MyFunction();

一堂课:

template<typename T>
class MyClass
{
public:

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

当我使用该类时,MyFunction<T>上的未定义符号错误 如果我将DoSomething更改为

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

一切正常,但这看起来像是一种解决方法,可能不适用于优化 我无法添加

template void MyFunction<T>;

到班级,因为它说它不能在课堂上。有没有其他方法可以强制实现函数的实例化?

编辑:
我能够编写一个失败的测试,但在g ++中它有一个不同的消息,实际上是编译器错误:http://ideone.com/RbMnh

3 个答案:

答案 0 :(得分:3)

您的代码也适用于优化。虽然,我不知道为什么简单m_Func = &MyFunction<T>不起作用。 GCC 4.3.4 compiles it fine。你正在使用哪种编译器?

你也可以这样做:

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

顺便说一下,函数指针类型定义不正确。它应该是这样的:

typedef void (*Function_T)();
                     //   ^^ put this!

答案 1 :(得分:3)

你的代码使用GCC编译得很好,所以我不确定这个解决方案是否解决了你的特定问题,但你可以显式地实例化模板函数,如下所示:

// Template function defined:
template <typename T>
void MyFunction() {
    // body
}

// Template function instantiated:
template void MyFunction<int>();

答案 2 :(得分:0)

问题可能是编译器错误,也可能是您未显示的代码部分中的错误。尝试构建一个重现问题的最小示例,这是我能够生成的最小示例,并且使用clang ++ 2.8和g ++ 4.4 / 4.5进行编译:

drodriguez@drodriguez-desktop:/tmp$ cat test.cpp 
#include <iostream>

template <typename T>
void function() {
}

template <typename T>
struct type {
    typedef void (*Func)();
    Func _f;
    void f() {
        _f = &function<T>;
    }
};

int main() {
    type<int> t;
    t.f();
    std::cout << t._f << std::endl;
}
drodriguez@drodriguez-desktop:/tmp$ /usr/bin/clang++ --version
clang version 2.8 (branches/release_28)
Target: x86_64-pc-linux-gnu
Thread model: posix
drodriguez@drodriguez-desktop:/tmp$ /usr/bin/clang++ -o test test.cpp && ./test
1
drodriguez@drodriguez-desktop:/tmp$ g++ --version
g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

drodriguez@drodriguez-desktop:/tmp$ g++-4.4 -o test test.cpp && ./test
1
相关问题