我想有一个很好的方法来启用我的强类型(例如 StockPrice、Count)的功能(例如++、*=、/)。
我不喜欢为此使用继承( CRTP/mixins ),我知道有些人可能喜欢它,但我不喜欢在这个用例中使用继承。
所以我有类似 this 的代码:
template<class, template<class...> class>
inline constexpr bool is_specialization = false;
template<template<class...> class T, class... Args>
inline constexpr bool is_specialization<T<Args...>, T> = true;
template<typename Underlying, typename TagType>
struct StrongT{
Underlying val;
using Tag = TagType;
};
template<typename T>
concept addable = is_specialization<T, StrongT> && requires (T& t){
typename T::Tag::addable_trait;
};
struct IndexTag{
using addable_trait = int;
};
using Index = StrongT<size_t, IndexTag>;
struct NanosTag{
using addable_trait = int;
};
using Nanos = StrongT<size_t, struct NanosTag>;
template<addable T>
T operator + (const T& a, const T& b){
return T{a.val+b.val};
}
我喜欢它,因为我可以在标签结构中列出我的“特征”,但我不喜欢它,因为它有点垃圾。我不能像这样内联声明标记结构: using Nanos = StrongT<size_t, struct NanosTag{/*...*/}>;
那么有没有办法在不使用继承的情况下以更短的方式做我想做的事?注意:我这里只有一个特征/概念,显然我希望支持许多特征,例如可比较/可增加...
最佳答案
怎么样的东西
// Different capability tags
struct Addable{};
struct PreIncrementable{};
// ...
template <typename Underlying,
typename TagType,
typename... CapabilityTags>
struct StrongT
{
Underlying val;
using Tag = TagType;
friend StrongT operator+(const StrongT& lhs, const StrongT& rhs)
requires((std::is_same_v<Addable, CapabilityTags> || ...))
{
return T{lhs.val + rhs.val};
}
StrongT& operator++()
requires((std::is_same_v<PreIncrementable, CapabilityTags> || ...))
{
++val;
return *this;
}
//...
};
进而struct NanosTag;
using Nanos = StrongT<size_t, NanosTag, Addable /*, ..*/>;
关于c++ - 使用 C++ 概念实现强类型的特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69030712/