[英]Deducing std::function with more than two args
我想知道為什么std::function
只知道兩個參數的函數。 我寫了一些運行良好的代碼,但是有很多限制。 任何反饋歡迎。 特別是,我懷疑我正在重新發明輪子。
我的代碼是關於ideone的 ,我將參考它。
例如,我可以用以下內容描述main
的類型:
function_type_deducer(main).describe_me();
// Output: I return i and I take 2 arguments. They are of type: i PPc
(其中'i'表示'int','PPc'表示指向指針指向char的指針)
標准std::function
不適用於具有兩個以上args的函數(請參閱我的代碼的最后兩行),但此代碼可以使用(示例代碼演示了三個arg函數)。 也許我的設計應該在標准庫中使用! 我定義了typedef tuple<Args...> args_as_tuple;
存儲所有args,而不僅僅是前兩個參數類型。
主要技巧是這個函數的推論:
template<class T, class... Args>
auto function_type_deducer(T(Args...)) -> Function__<T, Args...> {
return Function__<T, Args...> {};
}
限制:
function_type_deducer([](){}).describe_me();
x
和y
之間存在小的差異,因為y
采用string&
,其中x
表示string
。 (std :: function也沒有注意到這一點) 關於如何修復其中任何一個的任何想法? 我重新改造了車輪嗎?
這不會編譯
function_type_deducer([](){}).describe_me();
如果function_type_deducer
不是模板,它將起作用。 :)非捕獲lambdas(empty []
)可以隱式轉換為函數指針。 遺憾的是,對於某些模板參數推導,不考慮隱式轉換。 有關詳細信息,請參閱此問題 (請注意,我的答案並不完全正確,如評論所示)。
它沒有注意到x和y之間存在小的差異,因為y采用字符串&,其中x表示字符串。
這不是函數的問題,這是typeid
的一個問題,因為這個簡單的測試代碼顯示:
template<class T>
void x(void(T)){
T v;
(void)v;
}
void f1(int){}
void f2(int&){}
int main(){
x(f1);
x(f2);
}
Ideone上的實例 。 輸出:
錯誤:'v'聲明為引用但未初始化
一個簡單的修復可能是使用標簽分派:
#include <type_traits> // is_reference
#include <iostream>
#include <typeinfo>
template<class T>
void print_name(std::true_type){
std::cout << "reference to " << typeid(T).name();
}
template<class T>
void print_name(std::false_type){
std::cout << typeid(T).name();
}
template<class T>
void print_name(){
print_name(typename std::is_reference<T>::type());
}
並調用print_name<NextArg>()
而不是typeid(NextArg).name()
。
我重新改造了車輪嗎?
是的,有點和不,你沒有。 Boost.Function為所有參數( argN_type
樣式)提供typedef,以及其數量的靜態常量arity
。 但是,您無法輕松訪問這些typedef。 你需要一種迂回的方式來不意外地訪問不存在的方法。 tuple
想法效果最好,但它可以用更好的方式編寫。 這是我曾寫過的東西的修改版本:
#include <tuple>
#include <type_traits>
#include <iostream>
#include <typeinfo>
namespace detail{
template<class T>
std::ostream& print_name(std::ostream& os);
template<class T>
std::ostream& print_pointer(std::ostream& os, std::true_type){
typedef typename std::remove_pointer<T>:: type np_type;
os << "pointer to ";
return print_name<np_type>(os);
}
template<class T>
std::ostream& print_pointer(std::ostream& os, std::false_type){
return os << typeid(T).name();
}
template<class T>
std::ostream& print_name(std::ostream& os, std::true_type){
return os << "reference to " << typeid(T).name();
}
template<class T>
std::ostream& print_name(std::ostream& os, std::false_type){
return print_pointer<T>(os, typename std::is_pointer<T>::type());
}
template<class T>
std::ostream& print_name(std::ostream& os){
return print_name<T>(os, typename std::is_reference<T>::type());
}
// to workaround partial function specialization
template<unsigned> struct int2type{};
template<class Tuple, unsigned I>
std::ostream& print_types(std::ostream& os, int2type<I>){
typedef typename std::tuple_element<I,Tuple>::type type;
print_types<Tuple>(os, int2type<I-1>()); // left-folding
os << ", ";
return print_name<type>(os);
}
template<class Tuple>
std::ostream& print_types(std::ostream& os, int2type<0>){
typedef typename std::tuple_element<0,Tuple>::type type;
return print_name<type>(os);
}
} // detail::
template<class R, class... Args>
struct function_info{
typedef R result_type;
typedef std::tuple<Args...> argument_tuple;
static unsigned const arity = sizeof...(Args);
void describe_me(std::ostream& os = std::cout) const{
using namespace detail;
os << "I return '"; print_name<result_type>(os);
os << "' and I take '" << arity << "' arguments. They are: \n\t'";
print_types<argument_tuple>(os, int2type<arity-1>()) << "'\n";
}
};
Ideone上的實例 。 輸出:
main: I return 'i' and I take '2' arguments. They are:
'i, pointer to pointer to c'
x: I return 'Ss' and I take '3' arguments. They are:
'i, Ss, c'
y: I return 'Ss' and I take '3' arguments. They are:
'i, reference to Ss, c'
使用lambda函數的答案鏈接提供了關鍵提示:您需要獲取指向函數調用操作符的成員函數的指針。 也就是說,如果T
是一個函數對象,則需要查看&T::operator()
。 使用廣義SFINAE,您可以確定此函數調用運算符是否存在。 將這些東西放在一起可能有點迂回的方式,產生這個(用最新版本的gcc和clang編譯,除了lambda函數,不支持,但是,通過clang):
#include <iostream>
#include <sstream>
#include <string>
#include <typeinfo>
#include <functional>
#include <utility>
// -----------------------------------------------------------------------------
struct S {
void f(int, std::string&, void (*)(int)) {}
void g(int, std::string&, void (*)(int)) const {}
};
// -----------------------------------------------------------------------------
template <typename T> struct describer;
template <> struct describer<S>;
template <> struct describer<int>;
template <> struct describer<void>;
template <> struct describer<std::string>;
template <typename T> struct describer<T&>;
template <typename T> struct describer<T*>;
template <typename T> struct describer<T const>;
template <typename T> struct describer<T volatile>;
template <typename T> struct describer<T const volatile>;
template <typename T, int Size> struct describer<T(&)[Size]>;
template <typename T> struct describer {
static std::string type() { return "???"; }
};
template <> struct describer<S> {
static std::string type() { return "S"; }
};
template <> struct describer<void> {
static std::string type() { return "void"; }
};
template <> struct describer<int> {
static std::string type() { return "int"; }
};
template <> struct describer<std::string> {
static std::string type() { return "std::string"; }
};
template <typename T> struct describer<T&> {
static std::string type() { return describer<T>::type() + std::string("&"); }
};
template <typename T> struct describer<T&&> {
static std::string type() { return describer<T>::type() + std::string("&&"); }
};
template <typename T> struct describer<T*> {
static std::string type() { return describer<T>::type() + std::string("&"); }
};
template <typename T> struct describer<T const> {
static std::string type() { return describer<T>::type() + std::string(" const"); }
};
template <typename T> struct describer<T volatile> {
static std::string type() { return describer<T>::type() + std::string(" volatile"); }
};
template <typename T> struct describer<T const volatile> {
static std::string type() { return describer<T>::type() + std::string(" const volatile"); }
};
template <typename T, int Size> struct describer<T(&)[Size]>
{
static std::string type() {
std::ostringstream out;
out << "(array of " << Size << " " << describer<T>::type() << " objects)&";
return out.str();
}
};
template <typename... T> struct description_list;
template <> struct description_list<> { static std::string type() { return std::string(); } };
template <typename T> struct description_list<T> { static std::string type() { return describer<T>::type(); } };
template <typename T, typename... S> struct description_list<T, S...> {
static std::string type() { return describer<T>::type() + ", " + description_list<S...>::type(); }
};
template <typename R, typename... A>
struct describer<R(*)(A...)>
{
static std::string type() {
return "pointer function returning " + describer<R>::type() + " and taking arguments"
+ "(" + description_list<A...>::type() + ")";
}
};
template <typename R, typename S, typename... A>
struct describer<R(S::*)(A...)>
{
static std::string type() {
return "pointer to member function of " + describer<S>::type() + " returning " + describer<R>::type() + " "
"and taking arguments" + "(" + description_list<A...>::type() + ")";
}
};
template <typename R, typename S, typename... A>
struct describer<R(S::*)(A...) const>
{
static std::string type() {
return "pointer to const member function of " + describer<S>::type() + " returning " + describer<R>::type() + " "
"and taking arguments" + "(" + description_list<A...>::type() + ")";
}
};
template <typename T> char (&call_op(decltype(&T::operator())*))[1];
template <typename T> char (&call_op(...))[2];
template <typename T> struct has_function_call_operator { enum { value = sizeof(call_op<T>(0)) == 1 }; };
template <typename T>
typename std::enable_if<!has_function_call_operator<T>::value>::type describe(std::string const& what, T)
{
std::cout << "describe(" << what << ")=" << describer<T>::type() << "\n";
}
template <typename T>
typename std::enable_if<has_function_call_operator<T>::value>::type describe(std::string const& what, T)
{
std::cout << "describe(" << what << ")=function object: " << describer<decltype(&T::operator())>::type() << "\n";
}
int f(std::string, std::string const&, std::string&&) { return 0; }
int g(std::string&, std::string const&) { return 0; }
int main()
{
describe("int", 1);
describe("f", &f);
describe("g", &g);
describe("S::f", &S::f);
describe("S::g", &S::g);
describe("mini-lambda", []{}); // doesn't work with clang, yet.
describe("std::function<int(int(&)[1], int(&)[2], int(&)[4], int(&)[4])>",
std::function<int(int(&)[1], int(&)[2], int(&)[4], int(&)[4])>());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.