避免使用概念进行隐式转换
由于模板和动态多态不能很好地融合,我目前正在为Loggable
类型设计一个概念,而不是一个接口(用抽象类实现),它支持操作:
logger.log(LogLevel::info) << "some message" << 0 << 0.0 << 'c';
提供定义的日志级别:
enum class LogLevel
{
info,
warning,
error
};
这个概念是这样的:
template<typename T>
concept Loggable = requires(T v)
{
{
v.log(LogLevel{})
} -> std::convertible_to<T&>;
{
v << "log message" << static_cast<unsigned>(0) << static_cast<int>(0) << static_cast<float>(0.0)
<< static_cast<unsigned char>(0) << static_cast<char>('0')
} -> std::convertible_to<T&>;
};
为了测试记录器,定义了以下函数:
template<typename T>
requires Loggable<T>
void fun(T& v)
{
v.log(LogLevel::error);
}
我已经定义了Logger
:
struct Logger1
{
Logger1& log(LogLevel)
{
return *this;
}
Logger1& operator<<(float)
{
return *this;
}
Logger1& operator<<(std::string)
{
return *this;
}
};
然后使用:
调用记录器Logger1 l1{};
fun(l1);
不提供编译器错误。这是因为字符串文本被隐式转换为std::string和unsigned
,int
,char
,unsigned char
GET最终隐式转换为float
。
我该怎么做:
- 禁止
int
、char
、unsigned char
、unsigned
到float
的隐式强制转换,但... - 是否仍允许将字符串文本隐式强制转换为
std::string
?
解决方案
若要避免隐式转换,我们可以定义匹配所有其他类型的模板operator<<
。
此外,为了避免阻塞字符串文字,我们可以为thisoperator<<
添加一个约束,以确保操作数不会转换为std::string
:
#include <string>
template<typename T>
concept WeaklyLoggable = requires(T v) {
{ v.log(LogLevel{}) } -> std::convertible_to<T&>;
};
template<WeaklyLoggable T, class U>
requires (!std::convertible_to<U, std::string>)
auto operator<<(T, U) = delete;
template<typename T>
concept Loggable = WeaklyLoggable<T> && requires(T v) {
{
v << "log message"
<< static_cast<unsigned>(0)
<< static_cast<int>(0)
<< static_cast<float>(0.0)
<< static_cast<unsigned char>(0)
<< static_cast<char>('0')
} -> std::convertible_to<T&>;
};
Demo.
相关文章