![](/img/trans.png)
[英]Is there any way to make a constructor default values in a templated class?
[英]Any way to call a constructor (or any function/method) from data types without going through two templated functions?
constructor_caller<int,int,char*>(boxed_data);
template<typename ... CONSTRUCTOR_PARAMETER_TYPES>
static void constructor_caller(BoxedDataType & args) {
T * new_cpp_object = call_constructor_helper<CONSTRUCTOR_PARAMETER_TYPES...>(args,
std::index_sequence_for<CONSTRUCTOR_PARAMETER_TYPES...>());
}
template <typename ...Fs, size_t...ns>
static T * call_constructor_helper(BoxedDataType & args, std::index_sequence<ns...>){
// args contains the boxed parameters and CastToNative unboxes
// the value to a native c++ type
return new T(CastToNative<Fs>()(args[ns])...);
}
我有另一個解決方案涉及基於參數類型的HEAD,TAIL ...的遞歸繼承,但這甚至比這個例子更長。
另外,我認為將其概括為普通函數,對象方法和構造函數,我需要3個不同版本。 那是對的嗎?
你正在做很多事情。
將類型傳遞為值:
template<class T>struct tag_t{constexpr tag_t(){}; using type=T;};
template<class T>constexpr tag_t<T> tag={};
template<class Tag>using type=typename Tag::type;
將constexpr值作為類型傳遞:
template<std::size_t I>
using index_t=std::integral_constant<std::size_t,I>;
template<std::size_t I>
constexpr index_t<I> index={};
得到第n個arg:
const auto get_nth_from=[](auto&& src){
return [&src](auto index, auto tag)mutable->decltype(auto){
using F=type<decltype(tag)>;
return CastToNative<F>()(src[index]);
};
};
template<class T>
const auto construct=[](auto&&...args)->T*{
return new T(decltype(args)(args)...);
};
現在編寫在通用函數對象目標上運行的代碼。
namespace details {
template<class...Ts, std::size_t...Is, class F, class Get>
decltype(auto) call(std::index_sequence<Is...>, F&& f, Get&& get) {
return std::forward<F>(f)(get(index<Is>, tag<Ts>)...);
}
}
template<class...Ts, class F, class Get>
decltype(auto) call(F&& f, Get&& get) {
return details::call<Ts...>( std::index_sequence_for<Ts>{}, std::forward<F>(f), std::forward<Get>(get) );
}
完成所有這些工作之后, call_constructor
看起來像這樣:
template<class T, class...Ts>
T* call_constructor(BoxedDataType & args){
return call<Ts...>( construct<T>, get_nth_from(args) );
}
或者某些。
傳遞給call
一個目標構造一個T
,另一個調用一個方法,另一個調用自由函數。
有一件事將類型列表轉換為索引+類型然后調用函數成為一個操作。 將索引+類型轉換為args是另一回事。 把ctor變成了另一件可以打電話的人。 每個人做一件事,做得好。
一次操作的批量更多,但代碼重復更少,新操作也很容易。
以上使用C ++ 14簡潔,lambda作為一種風格問題。
代碼沒有編譯(寫在手機上),所以肯定包含錯別字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.