我有一個成員 func 模板如下:
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 應該在替代方案中恰好出現一次
為什么我得到這個?如何解決?
uj5u.com熱心網友回復:
我想我找到了答案:
該型別ArgValue_t是std::variant帶有引數的模板實體:bool/double/int/std::string,但不帶有int8_t/uint8_t/int16_t/uint16_t/...作為引數,因此在 的呼叫中get(),它只能接受bool/double/int/std::string作為模板 arg。
謝謝各位先生們,尤其是@Jarod42!!!
我可以抱怨gcc的訊息嗎?至少它可能會警告我 get() 的模板引數不正確?
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/375310.html
