gpt4 book ai didi

c++ - 是否可以在未推导所有模板参数的情况下获取模板成员函数的函数指针?

转载 作者:行者123 更新时间:2023-12-05 01:50:01 25 4
gpt4 key购买 nike

考虑下面的代码,是否可以获取operator()的函数指针?对于 Test2鉴于您拥有其所有模板参数?例如,假设我想要一个指向 operator()<float, double> 的函数指针其中 Args={float}Type2=double .

template<class Type1>
struct Test1
{
Type1 value;

template<class Type2, class ... Args>
bool operator()(const Type2& type)
{
//... Do something with Args... //
return type == value;
}
};

template<class Type1>
struct Test2
{
Type1 value;

template<class ... Args, class Type2>
bool operator()(const Type2& type)
{
//... Do something with Args... //
return type == value;
}
};

int main()
{
//OK!
auto ptr1 = &Test1<int>::template operator()<float, double>;
//Not ok! Assuming here that Args = {float, double}, Type2 = ?. Want: Args = {float}, Type2 = double
auto ptr2 = &Test2<int>::template operator()<float, double>;
}

我明白为什么像往常一样只向函数提供模板参数在这里不起作用。模板参数被推断为 Args={float, double}Type2被留下,因此编译错误。我认为,这一点从 Test1 的事实中可以明显看出。版本编译得很好。有没有解决的办法?谢谢。

最佳答案

你可以尝试这样声明它

bool (Test2<int>::*ptr2)(const double&) = &Test2<int>::template operator()<float>;

甚至

auto ptr3 = static_cast<bool (Test2<int>::*)(const double&)>(&Test2<int>::template operator()<float>);

关于c++ - 是否可以在未推导所有模板参数的情况下获取模板成员函数的函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73490666/

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