dimanche 26 mai 2019

error: conversion from 'fundamental type' to non-scalar type 'NamedType

I have the following structure (simplified enough to replicate the issue):

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; }
};

And then I attempt to use the assignment operator like this:

int main() {
    using NT_t = NamedType< int >;

    // generates error
    int t = 1;
    NT_t a = t;
    NT_t b = 2;
    // works fine
    NT_t c;
    c = 2;

    return 0;
}

I suspect that because I declare it and assign it at the same time it somehow attempts to use a constructor (which is explicit).

But I don't understand what's causing it and how to get around it.

Aucun commentaire:

Enregistrer un commentaire