【发布时间】:2021-09-10 02:13:51
【问题描述】:
(问题源于玩弄概念;不要认为这是一个必然的工程选择或任何事情。)
我试图指定满足概念的类型必须具有成员类型,并且该成员类型必须以某种方式可构造。作为一个最小的例子,它必须可以从 3 个整数构造。但我不知道如何正确表达:
#include <concepts>
template <typename T> concept Foo = requires {
typename T::TypeLikeThreeIntegers;
std::constructible_from<typename T::TypeLikeThreeIntegers, int, int, int>;
// I originally wrote
// std::constructible_from<T::TypeLikeThreeIntegers, int, int, int>;
// but compiler (clang++-12) gave an error and suggested the typename keyword
};
struct ThreeIntegers {
int x, y, z;
};
struct SatisfiesFoo {
using TypeLikeThreeIntegers = ThreeIntegers;
};
static_assert(Foo<SatisfiesFoo>);
// all is good so far
struct OnlyTwoIntegers {
int x, y;
};
struct ShouldNotSatisfyFoo {
using TypeLikeThreeIntegers = OnlyTwoIntegers;
};
static_assert(Foo<ShouldNotSatisfyFoo>);
// I expect this to fail but it doesn't!
int main() {
SatisfiesFoo::TypeLikeThreeIntegers v1{1, 2, 3};
// ShouldNotSatisfyFoo::TypeLikeThreeIntegers v2{1, 2, 3}; (error)
// would like the concept Foo to prevent such an error and give useful diagnostic
}
【问题讨论】:
标签: c++ c++20 c++-concepts