基本上,我需要一个static_cast
函数包装器作为谓词(用于转换),因为static_cast
不能直接以这种方式使用。 Lambda这次不是首选。我的实现:
template<typename T>
struct static_cast_forward{
template<class U>
T operator()(U&& u) const {
return static_cast<T>(std::forward<U>(u));
}
};
首先,虽然我对rvalue引用等有基本的了解,但我想验证这是否是实现此前向/包装器的正确方法?
第二,询问是否有任何std
或boost
库已经提供了此功能?
额外:您会以相同的方式转发其他演员吗?
实际案例:
我的实际情况是与boost::range
一起使用,例如:
//auto targetsRange = mixedRange | boost::adaptors::filtered(TYPECHECK_PRED) | boost::adaptors::transformed(static_cast_forward<TARGET_PTR_TYPE>());
工作示例:
#include <algorithm>
template<typename T>
struct static_cast_forward {
template<class U>
T operator()(U&& u) const {
return static_cast<T>(std::forward<U>(u));
}
};
//example 1:
void test1() {
std::vector<double> doubleVec{1.1, 1.2};
std::vector<int> intVec;
std::copy(doubleVec.begin(), doubleVec.end(), intVec.end());//not ok (compiles, but gives warning)
std::transform(doubleVec.begin(), doubleVec.end(), std::back_inserter(intVec), static_cast_forward<int>()); //ok
}
//example 2:
struct A {
virtual ~A() {}
};
struct B : public A {
};
struct C : public A {
};
void test2() {
std::vector<A*> vecOfA{ new B, new B};
std::vector<B*> vecOfB;
//std::transform(vecOfA.begin(), vecOfA.end(), std::back_inserter(vecOfB), static_cast<B*>); //not ok: syntax error..
std::transform(vecOfA.begin(), vecOfA.end(), std::back_inserter(vecOfB), static_cast_forward<B*>() ); //ok
}
答案 0 :(得分:2)
问题明确后的添加内容。
在两种情况下,您都不需要std::forward
,因为没有什么可移动的,因此只需要强制转换。但是,如果您也想泛化为可移动类型,那么您的实现对我来说似乎还不错。只是不要称它为forward
,因为它不是forward
。据我所知,std
中没有任何东西可以模仿您的struct
。
所以我只添加确实需要移动的test3()
:
struct B { };
struct D {
explicit D(B&&) { } // Note: explicit!
};
void test3()
{
std::vector<B> vb{B{}, B{}};
std::vector<D> vd;
// Won't compile because constructor is explicit
//std::copy(std::make_move_iterator(vb.begin()), std::make_move_iterator(vb.end()), std::back_inserter(vd));
// Works fine
std::transform(std::make_move_iterator(vb.begin()), std::make_move_iterator(vb.end()), std::back_inserter(vd), static_cast_forward<D>());
}
澄清了问题的答案。
如果我正确理解了您的意图,那么这就是您想要的:
template<typename T>
struct static_cast_forward {
template<class U>
decltype(auto) operator()(U&& u) const
{
if constexpr (std::is_lvalue_reference_v<U>)
return static_cast<T&>(u);
else
return static_cast<T&&>(u);
}
};
然后您拥有:
struct B { };
struct D : B { };
void foo() {
D d;
static_cast_forward<B> scf_as_B;
static_assert(std::is_same_v<decltype(scf_as_B(D{})), B&&>);
static_assert(std::is_same_v<decltype(scf_as_B(d)), B&>);
}