开发者

Compile error with pointer to template function in Visual Studio 2008

I'm trying to create a template class that stores a function pointer to a template function, but ran into a compile error in Visual Studio 2008. I created a simplified test case for it(see below) which still fails to compile in VS2008, but appeared to compile successfully on the online Comeau and online GCC compilers I tried.

The error I'm seeing is:

error C2436: 'func' : member function or nes开发者_StackOverflow中文版ted class in constructor initializer list
temp.cpp(21) : while compiling class template member function 'test_class<T>::test_class(T (__cdecl &))'
1>        with
1>        [
1>            T=int (const int &)
1>        ]

The same test using a non-template function works. Short of that, does anyone know a workaround for the issue, or if VS2008 is expecting some kind of different syntax for this?

Thanks,

Jerry

template<class T>
T template_function(const T& arg)
{
    return arg;
}

int non_template_function(const int& arg)
{
    return arg;
}

template<class T>
class test_class
{
public:
    test_class(const T& arg) : func(arg) {}
private:
    T func;
};

template<class T>
void create_class(const T& arg)
{
new test_class<T>(arg);
}

int main()
{
    create_class(&template_function<int>); //compile fails unless this is commented out
    create_class(&non_template_function);
    return 0;
}


Fix at two places;

T* func; //make this pointer type!

and,

 create_class(template_function<int>); //remove '&'
 create_class(non_template_function); //remove '&'

Done!


It seems like a compiler bug because it actually thinks that you are trying to invoke that function instead of initializing.

I don't have VS C++ compiler, but declaring T as a pointer may work around the problem:

template<class T>
class test_class
{
public:
    test_class(const T& arg) :
        func(&arg)
    {
    }

private:
    T *func;
};


template<class T>
void create_class(const T& arg)
{
    new test_class<T>(arg);
}

int main()
{
    create_class(template_function<int>); //compile fails unless this is commented out
    create_class(non_template_function);
}


It looks to me like the "const T& arg" in test_class and create_class are your problem. Changing those to a simple "T arg" seems to smooth things out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜