gpt4 book ai didi

c++ - 返回值是模板类型时如何使用std::result_of?

转载 作者:行者123 更新时间:2023-11-28 05:26:39 24 4
gpt4 key购买 nike

当 Callable 返回模板类型并收到以下错误 (clang++) 时,我正在尝试使用 result_of。我还提供了一个一切正常的简单案例。

错误:

main.cpp:22:50: note: candidate template ignored: could not match '<type-parameter-0-1>' against 'std::__1::shared_ptr<int> (*)()'
typename std::result_of<FunctionType<T>()>::type submit(FunctionType<T> f) {

代码:

    int f() {
int x = 1;
return x;
}

template<typename T>
std::shared_ptr<T> g() {
std::shared_ptr<T> x;
return x;
}

template <template<typename> class FunctionType, typename T>
typename std::result_of<FunctionType<T>()>::type submit(FunctionType<T> f) {

using result_type = typename std::result_of<FunctionType<T>()>::type;

result_type x;
return x;
}

template<typename FunctionType>
typename std::result_of<FunctionType()>::type submit2(FunctionType f) {

using result_type = typename std::result_of<FunctionType()>::type;

result_type x;
return x;
}


int main()
{
submit(g<int>); // error
submit2(f); // ok

return 0;
}

最佳答案

g<int>类型为 shared_ptr<int>()当由函数推导时,它会衰减为指向该类型的指针 ( shared_ptr<int>(*)() )。 FunctionTypesubmit因此不是模板,您不能在其上使用模板参数。

如果您能更清楚地了解您正在尝试做什么,我们可以找到解决您的主要问题的方法。

关于c++ - 返回值是模板类型时如何使用std::result_of?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40434145/

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