如何跨函式傳遞 std::plus 作為引數?
#include<functional>
#include<iostream>
template < class T, typename F >
T fn(T a, T b, F f)
{
return f<T>()(a,b);
}
template<class T>
struct X
{
template < typename F>
T foo(T a, T b, F f)
{
return fn<T, F>(a,b,f);
}
};
int main()
{
int a = 1;
int b = 1;
X<int> f;
std::cout<< f.foo(a,b, std::plus<int>);
return 0;
}
https://onlinegdb.com/g5NZc2x9V
main.cpp:7:21: 錯誤: ')' 標記之前的預期主運算式
uj5u.com熱心網友回復:
std::cout<< f.foo(a,b, std::plus<int>);
std::plus<int>是一種型別。就像int. 這失敗的原因完全相同,以下代碼也無法編譯:
void function(int n)
{
}
void another_function()
{
function(int);
}
由于不能作為引數傳遞std::plus的確切原因,您不能“作為引數傳遞” int。
What you can do, though -- and what you should do --- is to construct an instance of std::plus:
std::cout<< f.foo(a,b, std::plus<int>{});
Now, this passes an actual object, std::plus<int> to this function. However this is not going to be sufficient:
T fn(T a, T b, F f)
{
return f<T>()(a,b);
}
Here, f is going to be that std::plus<int> object. It is a callable object, so, well, all you have to do is call it:
T fn(T a, T b, F f)
{
return f(a,b);
}
uj5u.com熱心網友回復:
If you want to pass std::plus as a runtime argument you have to actually construct one.
You can't pass a type as an argument. Trying to pass a naked std::plus<int> is akin to writing a class name or type name there i.e. you would not expect foo(a,b, int) to compile if it expects the third argument to be an int value.
#include <functional>
#include <iostream>
template < class T, typename F >
T fn(T a, T b, F f)
{
return f(a, b);
}
template<class T>
struct X
{
template < typename F>
T foo(T a, T b, F f)
{
return fn<T, F>(a, b, f);
}
};
int main()
{
int a = 1;
int b = 1;
X<int> f;
std::cout << f.foo(a, b, std::plus<int>());
return 0;
}
uj5u.com熱心網友回復:
std::plus<int> is a type, not an object or function. So you cannot pass it to a function. You can however create an object of that type and pass that:
std::cout<< f.foo(a,b, std::plus<int>{});
Then in the call
return f<T>()(a,b);
the template arguments and first () make no sense. f is not a template, it is an object whose operator() you want to call, so:
return f(a,b);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/428018.html
