我想做这样的事情:
template <uint64_t N>
struct a {
static constexpr T1 v1 = {};
static constexpr T2 v2 = {};
static constexpr auto v3 = (N % 2 == 1 ? v1 : v2);
};但我不能对不同的类型使用(?:)。我怎么能做到这一点?
发布于 2020-08-29 19:35:42
如果你可以使用C++17 (但你只标记了C++11和C++14 ),那么基于if constexpr解决方案(非常优雅的基于Evg的lambda )是更好的选择。
在使用C++17之前,我想您可以尝试使用SFINAE。举例说明
#include <type_traits>
template <int N>
struct Foo
{
static constexpr int v1 = {};
static constexpr long v2 = {};
template <int M = N>
constexpr static std::enable_if_t<M % 2 == 1, int> getV3 ()
{ return v1; }
template <int M = N>
constexpr static std::enable_if_t<M % 2 != 1, long> getV3 ()
{ return v2; }
static constexpr auto v3 = getV3();
};
int main ()
{
static_assert( std::is_same_v<int const, decltype(Foo<1>::v3)> );
static_assert( std::is_same_v<long const, decltype(Foo<2>::v3)> );
}根据Evg的建议(谢谢!)您可以使用重载来避免SFINAE (良好的旧标记调度)。举例说明
template <int N>
struct Foo
{
static constexpr int v1 = {};
static constexpr long v2 = {};
constexpr static auto getV3 (std::true_type)
{ return v1; }
constexpr static auto getV3 (std::false_type)
{ return v2; }
static constexpr auto v3 = getV3(std::integral_constant<bool, N%2>{});
};https://stackoverflow.com/questions/63646394
复制相似问题