gpt4 book ai didi

C++容器内容特征混淆

转载 作者:行者123 更新时间:2023-11-28 00:17:01 25 4
gpt4 key购买 nike

我希望能够根据容器类内容的类型选择不同的类在编译时实例化。 Clang 和 GCC 都给出了下面代码的错误,所以我预计它有问题,即使它在使用 Visual Studio 时表现正确。有什么想法吗?

#include <iostream>

template <bool, class T = void>
struct enable_if {};

template <class T>
struct enable_if<true, T> {
typedef T type;
};

struct a {};
struct b {};

struct a_container {
typedef a contents_type;
};

struct b_container {
typedef b contents_type;
};

template <class T>
struct is_an_a { enum { value = false }; };

template <>
struct is_an_a<a> { enum { value = true }; };

template <class container_type>
struct container_traits {
typedef typename container_type::contents_type value_type;
};

template <class container_type>
struct is_an_a_container {
enum { value = typename is_an_a<typename container_traits<container_type>::value_type>::value };
};

template<class container_type, class enable = void>
struct S {
void operator()() {
std::cout << "Not an A\n";
}
};

template<class container_type>
struct S<container_type, typename enable_if<is_an_a_container<container_type>::value>::type> {
void operator()() {
std::cout << "Got an A\n";
}
};


int main() {
S<a_container>()();
S<b_container>()();

return 0;
}

在 Visual Studio 中,输出是:

Got an A
Not an A

GCC 失败:

35: error: expected `(' before '}' token

虽然 Clang 失败了:

35 : error: expected '(' for function-style cast or type construction

我可以通过将 is_an_a_container 的定义内联到 S 的第二个版本(例如下面)来解决这个问题,但在我看来它有点晦涩难懂我想了解错误。

template<class container_type>
struct S<container_type, typename enable_if<is_an_a<typename container_traits<container_type>::value_type>::value>::type> {
void operator()() {
std::cout << "Got an A\n";
}
};

或者也许有更简洁的解决方案来实现目标?注意:我必须使用 container_traits

最佳答案

template <class container_type>
struct is_an_a_container {
enum { value = typename is_an_a<typename conntainer_traits<container_type>::value_type>::value };
^^^^^^^^ ^^^^^ // this is not a type
};

只需删除类型名

template <class container_type>
struct is_an_a_container {
enum { value = is_an_a<typename conntainer_traits<container_type>::value_type>::value };

};

关于C++容器内容特征混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29562308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com