为什么继承会干扰编译器推理底层类型的能力?

问题描述 投票:0回答:1
template<typename T, typename Tuple>
struct has_type;

template<typename T>
struct has_type<T, std::tuple<>> : std::false_type {};

template<typename T, typename U, typename... Ts>
struct has_type<T, std::tuple<U, Ts...>> : has_type<T, std::tuple<Ts...>> {};

template<typename T, typename... Ts>
struct has_type<T, std::tuple<T, Ts...>> : std::true_type {};

template<typename T, typename Tuple>
using tuple_contains_type = typename has_type<T, Tuple>::type;

using FooTuple = std::tuple<int, float, bool>;

struct Foo : FooTuple {
    using TupleType = FooTuple;
};

int main() {

    // this compiles
    if constexpr (tuple_contains_type<float, Foo::TupleType>::value) {
        // ...
    }

    // this does not
    if constexpr (tuple_contains_type<float, Foo>::value) {
        // ...
    }

    return 0;
}

第一种情况可以编译,第二种情况则不能。我针对失败案例收到的错误是:

error C2794: 'type': is not a member of any direct or indirect base class of 'has_type<float,Foo>'
note: see reference to alias template instantiation 'tuple_contains_type<float,Foo>' being compiled
error C2938: 'tuple_contains_type' : Failed to specialize alias template
error C2039: 'value': is not a member of '`global namespace''
error C2059: syntax error: ')'
error C2143: syntax error: missing ';' before '{'

到期贷记; has_type 和 tuple_contains_type 的模板来自:How do I find out if a tuple contains a type?

c++ tuples template-meta-programming
1个回答
0
投票

问题是

struct has_type<float, Foo>
没有定义。模板实例化不会调用重载查找和转换。

© www.soinside.com 2019 - 2024. All rights reserved.