gpt4 book ai didi

c++ - 函数指针和类模板

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:28:57 24 4
gpt4 key购买 nike

我有一个使用以下类型的模板类 CFoo

enum My_Types {t1,t2};

特化由

template<My_Types T>
class CFoo
{
public:
CFoo()
{
std::cerr<<"ERROR:....";
exit(1);
}
};

template<>
class CFoo<t1>
{
....
};

此外,我还有一个使用 CFoo 对象作为参数的函数

template<class T>
void foo1 ( const T &CfooObj,...);

现在我需要一个指向 foo1 的指针,所以我必须指定模板参数

void (*foo1_pointer) ( const CFoo< t1 >&,...);

但以下似乎不正确(“不匹配转换函数 foo1...”):

foo1_pointer=&foo1;

如何正确传递这个模板函数的指针?

最佳答案

这可能是因为您的 GCC 编译器版本太旧。此代码在 GCC 4.7.2、Clang 3.2、ICC 13.0.1 和 VS10 上编译良好:

#include <iostream>

enum My_Types {t1,t2};

template<My_Types T>
class CFoo { /* ... */ };

template<> class CFoo<t1> { /* ... */ };

template<class T>
void foo1 (const T &, ...) { /* ... */ }

int main()
{
void (*foo1_pointer) (const CFoo< t1 >&, ...);
foo1_pointer = &foo1;
}

当从分配给它的函数指针的类型中获取地址时,编译器应该能够推断出 foo1 的模板参数。根据 C++11 标准的第 14.8.2.3/1 段:

Template arguments can be deduced from the type specified when taking the address of an overloaded function (13.4). The function template’s function type and the specified type are used as the types of P and A, and the deduction is done as described in 14.8.2.5.

此外,根据第 13.4/1 段:

A use of an overloaded function name without arguments is resolved in certain contexts to a function, a pointer to function or a pointer to member function for a specific function from the overload set. A function template name is considered to name a set of overloaded functions in such contexts. The function selected is the one whose type is identical to the function type of the target type required in the context. [...]

关于c++ - 函数指针和类模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14945564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com