我有以下结构(足够简单,可以重复这个问题):
template < class T, class P = struct NamedTypeDefaultTag > struct NamedType
{
//static_assert(std::is_fundamental_v< T >, "Template parameter is not a fundamental type.");
using ValueType = T;
ValueType m{};
constexpr NamedType() noexcept = default;
constexpr NamedType(const NamedType & value) noexcept = default;
constexpr NamedType(NamedType && value) noexcept = default;
constexpr explicit NamedType(const T & value) noexcept : m{value} { }
constexpr NamedType & operator = (const T & value) { m = value; return *this; }
};
然后我尝试像这样使用赋值运算符:
int main() {
using NT_t = NamedType< int >;
// generates error
int t = 1;
NT_t a = t;
const NT_t b = 2;
// works fine
NT_t c;
c = 2;
return 0;
}
我怀疑这是因为我同时声明并赋值它,它以某种方式试图使用构造函数(这是显式的)。
但我不明白是什么导致了它,也不知道如何绕过它。
发布于 2019-05-27 03:31:20
NT_t a = t;
尝试从int
到NT_t
的隐式转换。但是,能够执行此类转换的构造函数被标记为explicit
,因此无法在隐式转换中使用它。搞定
NT_t a{t};
const NT_t b{2};
https://stackoverflow.com/questions/56313049
复制相似问题