将类型从“static constexpr”推断为“using”
Deduce type from `static constexpr` to `using`
是否可以将 static constexpr
的类型“推断”为 using
?
https://compiler-explorer.com/z/hKzqhv7Pa
#include <chrono>
// Bar.h
using Bar = std::chrono::milliseconds;
static constexpr std::chrono::milliseconds BAR{100};
// Foo.h
struct Foo {
// Is there a way to get ride of the `using Bar`
// and "deduce" the type of `BAR` in a (elegant)
// way to the `using Type`?
using Type = Bar // decltype(BAR); // does not compile
static constexpr auto FOO = BAR;
};
int main() {
Foo::Type x{0};
x = Foo::FOO; // candidate function not viable: 'this' argument has type 'Foo::Type' (aka 'const duration<long, ratio<1, 1000> >'), but method is not marked const
return 0;
}
感谢您的帮助
兹拉坦
decltype(BAR)
确实有效。它只是返回一个 const 类型,因此 main
中的赋值失败。使用 std::remove_const_t<decltype(BAR)>
.
是否可以将 static constexpr
的类型“推断”为 using
?
https://compiler-explorer.com/z/hKzqhv7Pa
#include <chrono>
// Bar.h
using Bar = std::chrono::milliseconds;
static constexpr std::chrono::milliseconds BAR{100};
// Foo.h
struct Foo {
// Is there a way to get ride of the `using Bar`
// and "deduce" the type of `BAR` in a (elegant)
// way to the `using Type`?
using Type = Bar // decltype(BAR); // does not compile
static constexpr auto FOO = BAR;
};
int main() {
Foo::Type x{0};
x = Foo::FOO; // candidate function not viable: 'this' argument has type 'Foo::Type' (aka 'const duration<long, ratio<1, 1000> >'), but method is not marked const
return 0;
}
感谢您的帮助
兹拉坦
decltype(BAR)
确实有效。它只是返回一个 const 类型,因此 main
中的赋值失败。使用 std::remove_const_t<decltype(BAR)>
.