0

我有一个成员函数模板如下:

using ArgValue_t = std::variant<bool, double, int, std::string>;

struct Argument_t {
    enum Type_e { Bool, Double, Int, String, VALUES_COUNT };

    template<typename T>
    as( const Argument_t& def ) const;

    std::string name;
    ArgValue_t  valu;
    ArgValue_t  maxv;
    ArgValue_t  minv;
    Type_e      type = Int;
    int         prec = 0;
};

// specializing for bool
template<>
bool Argument_t::as<bool>( const Argument_t& def ) const {
    if( static_cast<Type_e>( valu.index() ) != Bool )
        return get<bool>( def.valu );

    return get<bool>( valu );
};

// specializing for double
template<>
double Argument_t::as<double>( const Argument_t& def ) const {
    if( static_cast<Type_e>( valu.index() ) != Double )
        return get<double>( def.valu );

    return min<double>( get<double>( def.maxv ),
                              max<double>( get<double>( def.minv ), get<double>( valu ) ) );
};

// specializing for string
template<>
string Argument_t::as<string>( const Argument_t& def ) const {
    if( static_cast<Type_e>( valu.index() ) != String )
        return get<string>( def.valu );

    return get<string>( valu );
};

// default version for all of integral types
template<typename T>
T Argument_t::as( const Argument_t& def ) const {
    if( static_cast<Type_e>( valu.index() ) != Int )
        return get<T>( def.valu );

    return min<T>( get<T>( def.maxv ),
                        max<T>( get<T>( def.minv ), get<T>( valu ) ) );
};

当我编译它时,我得到链接错误,所以我添加了一些它们的显式实例化。

// there is no problem with these three
template string Argument_t::as<string>( const Argument_t& ) const;
template bool Argument_t::as<bool>( const Argument_t& ) const;
template double Argument_t::as<double>( const Argument_t& ) const;

// but these six can **NOT** be compiled
template int8_t  Argument_t::as<int8_t>( const Argument_t& ) const;
template uint8_t  Argument_t::as<uint8_t>( const Argument_t& ) const;
template int16_t  Argument_t::as<int16_t>( const Argument_t& ) const;
template uint16_t  Argument_t::as<uint16_t>( const Argument_t& ) const;
template int32_t  Argument_t::as<int32_t>( const Argument_t& ) const;
template uint32_t  Argument_t::as<uint32_t>( const Argument_t& ) const;

编译器错误信息:

/usr/include/c++/9/variant:在 'constexpr const _Tp& std::get(const std::variant<_Types ...>&) [with _Tp = signed char; _Types = {bool, double, int, std::__cxx11::basic_string<char, std::char_traits, std::allocator >}]': Argument.cpp:57:16: 来自'T octopus::Argument_t: :as(const octopus::Argument_t&) const [with T = signed char]' Argument.cpp:67:53: 这里需要 /usr/include/c++/9/variant:1078:42: 错误: 静态

断言失败:T 应该在备选方案中只出现一次

为什么我得到这个?如何解决?

4

1 回答 1

0

我想我找到了答案:

该类型ArgValue_tstd::variant带有参数的模板实例:bool/double/int/std::string,但带有int8_t/uint8_t/int16_t/uint16_t/...作为参数,因此在 的调用中get(),它只能接受bool/double/int/std::string作为模板参数。

谢谢各位先生们,尤其是@Jarod42!!!

我可以投诉 gcc 的消息吗?至少它可能会警告我 get() 的模板参数不正确?

于 2021-11-23T14:19:54.130 回答