我遇到了 RValue 不允许隐式转换的问题。我的问题是什么实现更好地“绕过”这个限制?
这是说明问题的示例代码:
template<typename myVal>
class ITestClass
{
public:
virtual void myFunc(myVal item) = 0;
virtual myVal myFunc1() = 0;
};
class CTestClass : public ITestClass<int>
{
public:
void myFunc(int item) { }
int myFunc1() { return 0; }
};
template <typename T>
inline int CallFunction(std::shared_ptr< ITestClass<T> > ptrBase)
{
return 0;
}
inline std::shared_ptr< ITestClass<int> > GetBase()
{
return std::make_shared<CTestClass>();
}
std::shared_ptr< ITestClass<int> > ptrBase = std::make_shared<CTestClass>();
std::shared_ptr< CTestClass > ptrDerived = std::make_shared<CTestClass>();
CallFunction(ptrBase); // WORKS
CallFunction(GetBase()); // WORKS
CallFunction(std::make_shared<CTestClass>()); // ERROR
CallFunction(ptrDerived); // ERROR
可以使用 RValue 但函数需要基数且参数是派生失败的所有调用。
选项1
解决问题的选项 1:
CallFunction(std::static_pointer_cast< ITestClass<int> >(std::make_shared<CTestClass>()));
CallFunction(std::static_pointer_cast< ITestClass<int> >(ptrDerived));
此选项要求用户在调用函数之前将派生转换为基。这违背了一些目的,因为它要求调用者知道转换的实际基类型(也就是它是什么具体的模板实例化基类型)。
选项 2
解决问题的选项2:(修改模板和CallFunction一些)
template<typename myVal>
class ITestClass
{
public:
typedef myVal class_data_type;
virtual void myFunc(myVal item) = 0;
virtual myVal myFunc1() = 0;
};
class CTestClass : public ITestClass<int>
{
public:
void myFunc(int item) { }
int myFunc1() { return 0; }
};
template <typename T>
inline int CallFunction(std::shared_ptr<T> ptrBase)
{
static_assert(std::is_base_of<ITestClass<typename T::class_data_type>, T>::value, "Class needs to derive from ITestClass"); // some example of type checking
return 0;
}
CallFunction(std::make_shared<CTestClass>()); // now works as normal
CallFunction(ptrDerived); // now works as normal
我更喜欢选项 2,因为调用者不知道当前对 RValue 施加的限制,但我不确定是否有足够的类型检查 static_asserts 可以在有人传递错误参数时消除混淆。
问题
您认为选项 2 有什么问题吗?还是选项 1 仍然是更好的方法?
使用 SFINAE 有没有办法清理类型安全?