繁体   English   中英

有没有通过两个模板化函数从数据类型调用构造函数(或任何函数/方法)的方法?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM